package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.common.vo.excel.ExcelModelVO;
import com.bifang.module.base.common.vo.excel.ExcelVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.helper.ExcelCommonHelper;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.base.core.integration.ExcelIntegration;
import com.bifang.module.system.common.enums.CardTypeEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.*;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheVO;
import com.jwsoft.manager.common.vo.eduFormEnrollParams.EduFormEnrollParamsVO;
import com.jwsoft.manager.common.vo.eduHousehold.EduHouseholdVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.common.vo.eduSchoolConfig.EduSchoolConfigVO;
import com.jwsoft.manager.common.vo.eduStudentEnroll.BindEnrollQueryVO;
import com.jwsoft.manager.common.vo.eduStudentEnroll.BindEnrollVO;
import com.jwsoft.manager.common.vo.eduStudentEnroll.StudentEnrollCntVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollKindergarten.*;
import com.jwsoft.manager.common.vo.individuation.HouseHoldSaveVO;
import com.jwsoft.manager.common.vo.individuation.HouseInterfaceSaveVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.*;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 幼儿园报名管理业务实现类
 *
 * @author chenzh
 * @since 2023-02-10
 */
@ApiService(funcCode = "kindergarten", title = "幼儿园报名管理")
public class EduStudentEnrollKindergartenIntegrationImpl implements EduStudentEnrollKindergartenIntegration {

    @Autowired
    public EduStudentEnrollKindergartenService eduStudentEnrollKindergartenService;
    @Autowired
    private EduSystemConfigIntegration eduSystemConfigIntegration;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private DictHelper dictHelper;
    @Autowired
    private ExcelCommonHelper excelCommonHelper;
    @Autowired
    private EduSchoolConfigService eduSchoolConfigService;
    @Autowired
    private EduSchoolService eduSchoolService;
    @Autowired
    private EduFormEnrollService eduFormEnrollService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    public ExcelIntegration excelIntegration;
    @Value("${spring.servlet.multipart.location}")
    private String tempPath;
    @Autowired
    private RedisHelper redisHelper;
    @Autowired
    private EduEnrollClearCacheHelper enrollClearCacheHelper;

    @Autowired
    private EduHouseholdIntegration eduHouseholdIntegration;

    @Autowired
    private EduHouseIntegration eduHouseIntegration;

    @Autowired
    private EduEnrollmenBrochureService eduEnrollmenBrochureService;

    @Autowired
    private DictIntegration dictIntegration;

    public static final String REDIS_YHDR = "KINDERGARTENAPPLY:yhdr:";
    @Autowired
    private EduDataTaskDetailService eduDataTaskDetailService;

    @Autowired
    public EduhStudentEnrollKindergartenService eduhStudentEnrollKindergartenService;
    public static final String handleTable = "edu_student_enroll_kindergarten";
    @Override
    @OpApi(funcCode = "kindergarten0001", title = "幼儿园报名管理分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentEnrollKindergartenVO> getList(EduStudentEnrollKindergartenQueryVO vo) {
        if(vo.getYear()==null){
            throw new AppException("查询年度不能为空");
        }
        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAreaCode())){
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
        }else {
            areaCodeList.add(vo.getAreaCode());
        }
        if (CollectionUtils.isEmpty(areaCodeList)){
            throw new AppException("必须传入行政区划");
        }
        if(vo.getManagerFlag()!=null&&!vo.getManagerFlag()){
            if(StringUtils.isBlank(vo.getSchoolId())){
                vo.setSchoolId(SessionUtil.getOrgId());
            }
        }

        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取50条
            vo.setPageNum(1);
            vo.setPageSize(50);
        }
        //根据任务判断是否当前年度处理过迁移数据
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),handleTable);
        if (!queryHistoryFlag) {
            LambdaQueryWrapper<EduStudentEnrollKindergarten> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(!ObjectUtils.isEmpty(vo.getYear()), EduStudentEnrollKindergarten::getYear, vo.getYear())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getEnrollStatus()),
                            EduStudentEnrollKindergarten::getEnrollStatus,
                            vo.getEnrollStatus())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getSource()),
                            EduStudentEnrollKindergarten::getSource,
                            vo.getSource())
                    .in(
                            EduStudentEnrollKindergarten::getAreaCode,
                            areaCodeList)
                    .like(
                            !ObjectUtils.isEmpty(vo.getChildFullName()),
                            EduStudentEnrollKindergarten::getChildFullName,
                            vo.getChildFullName())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getChildIdcard()),
                            EduStudentEnrollKindergarten::getChildIdcard,
                            vo.getChildIdcard())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getConfigName()),
                            EduStudentEnrollKindergarten::getConfigName,
                            vo.getConfigName())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getChildCardType()),
                            EduStudentEnrollKindergarten::getChildCardType,
                            vo.getChildCardType())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getBirthYmd()),
                            EduStudentEnrollKindergarten::getBirthYmd,
                            vo.getBirthYmd())
                    .eq(!ObjectUtils.isEmpty(vo.getSex()), EduStudentEnrollKindergarten::getSex, vo.getSex())
                    .like(
                            !ObjectUtils.isEmpty(vo.getChildShortName()),
                            EduStudentEnrollKindergarten::getChildShortName,
                            vo.getChildShortName())
                    .like(
                            !ObjectUtils.isEmpty(vo.getHouseholdPlace()),
                            EduStudentEnrollKindergarten::getHouseholdPlace,
                            vo.getHouseholdPlace())
                    .like(
                            !ObjectUtils.isEmpty(vo.getAddress()),
                            EduStudentEnrollKindergarten::getAddress,
                            vo.getAddress())
                    .like(
                            !ObjectUtils.isEmpty(vo.getFatherName()),
                            EduStudentEnrollKindergarten::getFatherName,
                            vo.getFatherName())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getFatherIdcard()),
                            EduStudentEnrollKindergarten::getFatherIdcard,
                            vo.getFatherIdcard())
                    .like(
                            !ObjectUtils.isEmpty(vo.getFatherWork()),
                            EduStudentEnrollKindergarten::getFatherWork,
                            vo.getFatherWork())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getFatherPhone()),
                            EduStudentEnrollKindergarten::getFatherPhone,
                            vo.getFatherPhone())
                    .like(
                            !ObjectUtils.isEmpty(vo.getMotherName()),
                            EduStudentEnrollKindergarten::getMotherName,
                            vo.getMotherName())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getMotherIdcard()),
                            EduStudentEnrollKindergarten::getMotherIdcard,
                            vo.getMotherIdcard())
                    .like(
                            !ObjectUtils.isEmpty(vo.getMotherWork()),
                            EduStudentEnrollKindergarten::getMotherWork,
                            vo.getMotherWork())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getMotherPhone()),
                            EduStudentEnrollKindergarten::getMotherPhone,
                            vo.getMotherPhone())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getAuthStatus()),
                            EduStudentEnrollKindergarten::getAuthStatus,
                            vo.getAuthStatus())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getConfigType()),
                            EduStudentEnrollKindergarten::getConfigType,
                            vo.getConfigType())
                    .eq(!ObjectUtils.isEmpty(vo.getSchoolId()), EduStudentEnrollKindergarten::getSchoolId, vo.getSchoolId());
            if (StringUtils.isNotBlank(vo.getAdmitFlag())) {
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(vo.getAdmitFlag())) {
                    queryWrapper.eq(EduStudentEnrollKindergarten::getAdmitFlag, vo.getAdmitFlag());
                } else if (BoolEnum.FALSE.getType().equalsIgnoreCase(vo.getAdmitFlag())) {
                    queryWrapper.eq(EduStudentEnrollKindergarten::getAdmitFlag, vo.getAdmitFlag());
                } else {
                    queryWrapper.isNull(EduStudentEnrollKindergarten::getAdmitFlag);
                }
            }
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduStudentEnrollKindergarten> list = eduStudentEnrollKindergartenService.list(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduStudentEnrollKindergarten> pageInfo = new PageInfo<>(list);
            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduStudentEnrollKindergartenVO> resultList = Convert.toList(EduStudentEnrollKindergartenVO.class, pageInfo.getList());
            // 转义数据字典值
            dictHelper.valueToName(resultList, Arrays.asList(EduEnrollKindergartenDictEnum.values()));
            for (EduStudentEnrollKindergartenVO studentEnrollKindergartenVO : resultList) {
                if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getSchoolId())) {
                    EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(studentEnrollKindergartenVO.getSchoolId());
                    if (eduSchoolVO != null) {
                        studentEnrollKindergartenVO.setSchoolName(eduSchoolVO.getSchoolName());
                    }
                }
                studentEnrollKindergartenVO.setApplyIdString(studentEnrollKindergartenVO.getApplyId() + "");
            }
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }else {
            // 迁移过后，判断是否加密
            Boolean encryptFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), handleTable));
            //如果加密，把查询条件加密
            if (encryptFlag) {
                if (StringUtils.isNotBlank(vo.getChildFullName())){
                    vo.setChildFullName(CommonSecureUtil.sm4Encrypt(vo.getChildFullName()));
                }
                if (StringUtils.isNotBlank(vo.getChildIdcard())){
                    vo.setChildIdcard(CommonSecureUtil.sm4Encrypt(vo.getChildIdcard()));
                }
                if (StringUtils.isNotBlank(vo.getChildShortName())){
                    vo.setChildShortName(CommonSecureUtil.sm4Encrypt(vo.getChildShortName()));
                }
                if (StringUtils.isNotBlank(vo.getAddress())){
                    vo.setAddress(CommonSecureUtil.sm4Encrypt(vo.getAddress()));
                }
                if (StringUtils.isNotBlank(vo.getFatherName())){
                    vo.setFatherName(CommonSecureUtil.sm4Encrypt(vo.getFatherName()));
                }
                if (StringUtils.isNotBlank(vo.getFatherIdcard())){
                    vo.setFatherName(CommonSecureUtil.sm4Encrypt(vo.getFatherIdcard()));
                }
                if (StringUtils.isNotBlank(vo.getFatherPhone())){
                    vo.setFatherPhone(CommonSecureUtil.sm4Encrypt(vo.getFatherPhone()));
                }
                if (StringUtils.isNotBlank(vo.getMotherName())){
                    vo.setMotherName(CommonSecureUtil.sm4Encrypt(vo.getMotherName()));
                }
                if (StringUtils.isNotBlank(vo.getMotherIdcard())){
                    vo.setMotherIdcard(CommonSecureUtil.sm4Encrypt(vo.getMotherIdcard()));
                }
                if (StringUtils.isNotBlank(vo.getMotherPhone())){
                    vo.setMotherPhone(CommonSecureUtil.sm4Encrypt(vo.getMotherPhone()));
                }
            }
            LambdaQueryWrapper<EduhStudentEnrollKindergarten> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(!ObjectUtils.isEmpty(vo.getYear()), EduhStudentEnrollKindergarten::getYear, vo.getYear())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getEnrollStatus()),
                            EduhStudentEnrollKindergarten::getEnrollStatus,
                            vo.getEnrollStatus())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getSource()),
                            EduhStudentEnrollKindergarten::getSource,
                            vo.getSource())
                    .in(
                            EduhStudentEnrollKindergarten::getAreaCode,
                            areaCodeList)
                    .like(
                            !ObjectUtils.isEmpty(vo.getChildFullName()),
                            EduhStudentEnrollKindergarten::getChildFullName,
                            vo.getChildFullName())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getChildIdcard()),
                            EduhStudentEnrollKindergarten::getChildIdcard,
                            vo.getChildIdcard())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getConfigName()),
                            EduhStudentEnrollKindergarten::getConfigName,
                            vo.getConfigName())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getChildCardType()),
                            EduhStudentEnrollKindergarten::getChildCardType,
                            vo.getChildCardType())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getBirthYmd()),
                            EduhStudentEnrollKindergarten::getBirthYmd,
                            vo.getBirthYmd())
                    .eq(!ObjectUtils.isEmpty(vo.getSex()), EduhStudentEnrollKindergarten::getSex, vo.getSex())
                    .like(
                            !ObjectUtils.isEmpty(vo.getChildShortName()),
                            EduhStudentEnrollKindergarten::getChildShortName,
                            vo.getChildShortName())
                    .like(
                            !ObjectUtils.isEmpty(vo.getHouseholdPlace()),
                            EduhStudentEnrollKindergarten::getHouseholdPlace,
                            vo.getHouseholdPlace())
                    .like(
                            !ObjectUtils.isEmpty(vo.getAddress()),
                            EduhStudentEnrollKindergarten::getAddress,
                            vo.getAddress())
                    .like(
                            !ObjectUtils.isEmpty(vo.getFatherName()),
                            EduhStudentEnrollKindergarten::getFatherName,
                            vo.getFatherName())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getFatherIdcard()),
                            EduhStudentEnrollKindergarten::getFatherIdcard,
                            vo.getFatherIdcard())
                    .like(
                            !ObjectUtils.isEmpty(vo.getFatherWork()),
                            EduhStudentEnrollKindergarten::getFatherWork,
                            vo.getFatherWork())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getFatherPhone()),
                            EduhStudentEnrollKindergarten::getFatherPhone,
                            vo.getFatherPhone())
                    .like(
                            !ObjectUtils.isEmpty(vo.getMotherName()),
                            EduhStudentEnrollKindergarten::getMotherName,
                            vo.getMotherName())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getMotherIdcard()),
                            EduhStudentEnrollKindergarten::getMotherIdcard,
                            vo.getMotherIdcard())
                    .like(
                            !ObjectUtils.isEmpty(vo.getMotherWork()),
                            EduhStudentEnrollKindergarten::getMotherWork,
                            vo.getMotherWork())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getMotherPhone()),
                            EduhStudentEnrollKindergarten::getMotherPhone,
                            vo.getMotherPhone())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getAuthStatus()),
                            EduhStudentEnrollKindergarten::getAuthStatus,
                            vo.getAuthStatus())
                    .eq(
                            !ObjectUtils.isEmpty(vo.getConfigType()),
                            EduhStudentEnrollKindergarten::getConfigType,
                            vo.getConfigType())
                    .eq(!ObjectUtils.isEmpty(vo.getSchoolId()), EduhStudentEnrollKindergarten::getSchoolId, vo.getSchoolId());
            if (StringUtils.isNotBlank(vo.getAdmitFlag())) {
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(vo.getAdmitFlag())) {
                    queryWrapper.eq(EduhStudentEnrollKindergarten::getAdmitFlag, vo.getAdmitFlag());
                } else if (BoolEnum.FALSE.getType().equalsIgnoreCase(vo.getAdmitFlag())) {
                    queryWrapper.eq(EduhStudentEnrollKindergarten::getAdmitFlag, vo.getAdmitFlag());
                } else {
                    queryWrapper.isNull(EduhStudentEnrollKindergarten::getAdmitFlag);
                }
            }
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduhStudentEnrollKindergarten> list = eduhStudentEnrollKindergartenService.list(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduhStudentEnrollKindergarten> pageInfo = new PageInfo<>(list);
            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduStudentEnrollKindergartenVO> resultList = Convert.toList(EduStudentEnrollKindergartenVO.class, pageInfo.getList());
            // 转义数据字典值
            dictHelper.valueToName(resultList, Arrays.asList(EduEnrollKindergartenDictEnum.values()));
            for (EduStudentEnrollKindergartenVO studentEnrollKindergartenVO : resultList) {
                if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getSchoolId())) {
                    if ("1".equals(studentEnrollKindergartenVO.getEncryptFlag())) {
                        if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getChildFullName())){
                            studentEnrollKindergartenVO.setChildFullName(CommonSecureUtil.sm4Decrypt(studentEnrollKindergartenVO.getChildFullName()));
                        }
                        if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getChildIdcard())){
                            studentEnrollKindergartenVO.setChildIdcard(CommonSecureUtil.sm4Decrypt(studentEnrollKindergartenVO.getChildIdcard()));
                        }
                        if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getChildShortName())){
                            studentEnrollKindergartenVO.setChildShortName(CommonSecureUtil.sm4Decrypt(studentEnrollKindergartenVO.getChildShortName()));
                        }
                        if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getAddress())){
                            studentEnrollKindergartenVO.setAddress(CommonSecureUtil.sm4Decrypt(studentEnrollKindergartenVO.getAddress()));
                        }
                        if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getFatherName())){
                            studentEnrollKindergartenVO.setFatherName(CommonSecureUtil.sm4Decrypt(studentEnrollKindergartenVO.getFatherName()));
                        }
                        if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getFatherIdcard())){
                            studentEnrollKindergartenVO.setFatherName(CommonSecureUtil.sm4Decrypt(studentEnrollKindergartenVO.getFatherIdcard()));
                        }
                        if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getFatherPhone())){
                            studentEnrollKindergartenVO.setFatherPhone(CommonSecureUtil.sm4Decrypt(studentEnrollKindergartenVO.getFatherPhone()));
                        }
                        if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getMotherName())){
                            studentEnrollKindergartenVO.setMotherName(CommonSecureUtil.sm4Decrypt(studentEnrollKindergartenVO.getMotherName()));
                        }
                        if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getMotherIdcard())){
                            studentEnrollKindergartenVO.setMotherIdcard(CommonSecureUtil.sm4Decrypt(studentEnrollKindergartenVO.getMotherIdcard()));
                        }
                        if (StringUtils.isNotBlank(studentEnrollKindergartenVO.getMotherPhone())){
                            studentEnrollKindergartenVO.setMotherPhone(CommonSecureUtil.sm4Decrypt(studentEnrollKindergartenVO.getMotherPhone()));
                        }
                    }
                    EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(studentEnrollKindergartenVO.getSchoolId());
                    if (eduSchoolVO != null) {
                        studentEnrollKindergartenVO.setSchoolName(eduSchoolVO.getSchoolName());
                    }
                }
                studentEnrollKindergartenVO.setApplyIdString(studentEnrollKindergartenVO.getApplyId() + "");
            }
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }
    }

    @Override
    @OpApi(funcCode = "kindergarten0002", title = "幼儿园报名管理根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduStudentEnrollKindergartenVO getById(EduStudentEnrollKindergartenKeyVO vo) {
        //判断是否迁移过
        EduStudentEnrollKindergartenVO result;
        Boolean queryHistoryFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyQueryHistory(vo.getYear(), handleTable));
        if (!queryHistoryFlag) {
            EduStudentEnrollKindergarten entity = eduStudentEnrollKindergartenService.getById(vo.getFormDetailId());
            if (ObjectUtils.isEmpty(entity)) {
                throw new AppException("查询不到详细信息!");
            }
            result = Convert.convert(EduStudentEnrollKindergartenVO.class, entity);
        } else {
            EduhStudentEnrollKindergarten kindergarten = eduhStudentEnrollKindergartenService.getById(vo.getFormDetailId());
            if (ObjectUtils.isEmpty(kindergarten)) {
                throw new AppException("查询不到详细信息!");
            }
            if ("1".equals(kindergarten.getEncryptFlag())) {
                if (StringUtils.isNotBlank(kindergarten.getChildFullName())) {
                    kindergarten.setChildFullName(CommonSecureUtil.sm4Decrypt(kindergarten.getChildFullName()));
                }
                if (StringUtils.isNotBlank(kindergarten.getChildIdcard())) {
                    kindergarten.setChildIdcard(CommonSecureUtil.sm4Decrypt(kindergarten.getChildIdcard()));
                }
                if (StringUtils.isNotBlank(kindergarten.getChildShortName())) {
                    kindergarten.setChildShortName(CommonSecureUtil.sm4Decrypt(kindergarten.getChildShortName()));
                }
                if (StringUtils.isNotBlank(kindergarten.getAddress())) {
                    kindergarten.setAddress(CommonSecureUtil.sm4Decrypt(kindergarten.getAddress()));
                }
                if (StringUtils.isNotBlank(kindergarten.getFatherName())) {
                    kindergarten.setFatherName(CommonSecureUtil.sm4Decrypt(kindergarten.getFatherName()));
                }
                if (StringUtils.isNotBlank(kindergarten.getFatherIdcard())) {
                    kindergarten.setFatherName(CommonSecureUtil.sm4Decrypt(kindergarten.getFatherIdcard()));
                }
                if (StringUtils.isNotBlank(kindergarten.getFatherPhone())) {
                    kindergarten.setFatherPhone(CommonSecureUtil.sm4Decrypt(kindergarten.getFatherPhone()));
                }
                if (StringUtils.isNotBlank(kindergarten.getMotherName())) {
                    kindergarten.setMotherName(CommonSecureUtil.sm4Decrypt(kindergarten.getMotherName()));
                }
                if (StringUtils.isNotBlank(kindergarten.getMotherIdcard())) {
                    kindergarten.setMotherIdcard(CommonSecureUtil.sm4Decrypt(kindergarten.getMotherIdcard()));
                }
                if (StringUtils.isNotBlank(kindergarten.getMotherPhone())) {
                    kindergarten.setMotherPhone(CommonSecureUtil.sm4Decrypt(kindergarten.getMotherPhone()));
                }
            }
            result = Convert.convert(EduStudentEnrollKindergartenVO.class, kindergarten);

        }

        dictHelper.valueToName(result, Arrays.asList(EduEnrollKindergartenDictEnum.values()));
        if(StringUtils.isNotBlank(result.getSchoolId())){
            EduSchoolVO eduSchoolVO=eduSchoolService.getDetail(result.getSchoolId());
            if(eduSchoolVO!=null){
                result.setSchoolName(eduSchoolVO.getSchoolName());
            }

        }
        if(StringUtils.isBlank(result.getAdmitFlag())){
            //待录取为2
            result.setAdmitFlag("2");
        }
        if(StringUtils.isBlank(result.getChildCardType())){
            result.setChildCardType(CardTypeEnum.idcard.getType());
        }
        if(StringUtils.isBlank(result.getFatherCardType())){
            result.setFatherCardType(CardTypeEnum.idcard.getType());
        }
        if(StringUtils.isBlank(result.getMotherCardType())){
            result.setMotherCardType(CardTypeEnum.idcard.getType());
        }
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "kindergarten0003", title = "幼儿园报名管理保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduStudentEnrollKindergartenVO vo) {
        if (ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }
        if (ObjectUtils.isEmpty(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        //主键为空为新增校验
        if (StringUtils.isBlank(vo.getChildCardType())) {
            // 为空默认为身份证
            vo.setChildCardType(CardTypeEnum.idcard.getType());
        }
        if (StringUtils.isBlank(vo.getFatherCardType())) {
            // 为空默认为身份证
            vo.setFatherCardType(CardTypeEnum.idcard.getType());
        }
        if (StringUtils.isBlank(vo.getMotherCardType())) {
            // 为空默认为身份证
            vo.setMotherCardType(CardTypeEnum.idcard.getType());
        }
        if (CardTypeEnum.idcard.getType().equals(vo.getChildCardType())) {
            if (!IdcardUtil.isValidCard(vo.getChildIdcard())) {
                throw new AppException("幼儿身份证有误！");
            } else {
                // 设置性别和出生日期
                vo.setBirthYmd(IdcardUtil.getBirth(vo.getChildIdcard()));
                if (StringUtils.isBlank(vo.getSex())) {
                    int gender = IdcardUtil.getGenderByIdCard(vo.getChildIdcard());
                    if (gender == 1) {
                        // 男
                        vo.setSex("1");
                    } else {
                        // 女
                        vo.setSex("2");
                    }
                }
            }
        } else {
            if (IdcardUtil.isValidCard(vo.getChildIdcard())) {
                throw new AppException("请选择正确的证件类型！");
            }
            if (StringUtils.isBlank(vo.getSex())) {
                throw new AppException("幼儿性别不能为空！");
            }
            if (StringUtils.isBlank(vo.getBirthYmd())) {
                throw new AppException("幼儿出生日期不能为空！");
            }
            vo.setBirthYmd(vo.getBirthYmd().replaceAll("-", ""));
        }
        boolean flag = true;
        if (!ObjectUtils.isEmpty(vo.getMotherIdcard())) {
            boolean motherFlag = IdcardUtil.isValidCard(vo.getMotherIdcard());
            if (com.jwsoft.manager.common.enums.CardTypeEnum.idcard.getType().equals(vo.getMotherCardType()) && !motherFlag) {
                throw new AppException("母亲身份证有误！");
            } else {
                if (motherFlag && !com.jwsoft.manager.common.enums.CardTypeEnum.idcard.getType().equals(vo.getMotherCardType())) {
                    throw new AppException("母亲证件类型，请选择身份证！");
                }
                vo.setMotherIdcard(vo.getMotherIdcard().trim().toUpperCase());
            }
            if (ObjectUtils.isEmpty(vo.getMotherName())) {
                throw new AppException("母亲姓名不能为空！");
            } else {
                vo.setMotherName(
                        Validator.isChinese(vo.getMotherName())
                                ? vo.getMotherName().replace(" ", "").trim()
                                : vo.getMotherName().trim());
            }
            flag = false;
        }

        if (!ObjectUtils.isEmpty(vo.getFatherIdcard())) {
            boolean fatherFlag = IdcardUtil.isValidCard(vo.getFatherIdcard());
            if (com.jwsoft.manager.common.enums.CardTypeEnum.idcard.getType().equals(vo.getFatherCardType()) && !fatherFlag) {
                throw new AppException("父亲(监护人)身份证有误！");
            } else {
                if (fatherFlag && !com.jwsoft.manager.common.enums.CardTypeEnum.idcard.getType().equals(vo.getFatherCardType())) {
                    throw new AppException("父亲(监护人)证件类型，请选择身份证！");
                }
                vo.setFatherIdcard(vo.getFatherIdcard().trim().toUpperCase());
            }
            if (ObjectUtils.isEmpty(vo.getFatherName())) {
                throw new AppException("父亲(监护人)姓名不能为空！");
            } else {
                vo.setFatherName(
                        Validator.isChinese(vo.getFatherName())
                                ? vo.getFatherName().replace(" ", "").trim()
                                : vo.getFatherName().trim());
            }
            flag = false;
        }
        if (ObjectUtils.isEmpty(vo.getChildFullName())) {
            throw new AppException("学生姓名不能为空！");
        } else {
            vo.setChildFullName(
                    Validator.isChinese(vo.getChildFullName())
                            ? vo.getChildFullName().replace(" ", "").trim()
                            : vo.getChildFullName().trim());
        }
        if (flag) {
            throw new AppException("父亲（监护人）或母亲一方必填");
        }

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "kindergarten0004", title = "幼儿园报名管理新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "kindergarten0004",
            operationName = "幼儿园报名管理新增",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    public EduStudentEnrollKindergartenVO add(EduStudentEnrollKindergartenVO vo) {
        if (StringUtils.isBlank(vo.getSchoolId())) {
            throw new AppException("请先选择报名学校");
        }
        String bmKey = EduCache.EDU_ENROLL_KINDERGARTEN_ZS + vo.getChildIdcard();
        redisHelper.del(bmKey);
        if (redisHelper.hasKey(bmKey)) {
            throw new AppException("该幼儿已提交报名，如遇到问题，请等待10分钟后再试");
        }
        if(vo.getCheckAge()==null){
            vo.setCheckAge(true);
        }
        if(vo.getCheckEnrollTime()==null){
            vo.setCheckEnrollTime(true);
        }
        if(StringUtils.isBlank(vo.getSource())){
            vo.setSource("2");
        }
        if(StringUtils.isBlank(vo.getFormType())){
            vo.setFormType(EduFormTypeEnum.NURSERYENROLL.getType());
        }

        int year = eduHelper.thisYear();
        vo.setYear(year);
        Long curDateTime = DateUtil.currentSeconds();
        checkSave(vo);
        /***
         CommonVO commonVO=new CommonVO();
         commonVO.setParamKey("test_flag");
         String testFlagStr=commonIntegration.getValueByKey(commonVO);
         ***/
        boolean testFlag=false;//是否测试模式，测试模式下放弃一些校验
        /***
         if(BoolEnum.TRUE.getType().equalsIgnoreCase(testFlagStr)||"true".equalsIgnoreCase(testFlagStr)){
         testFlag=true;
         }***/
        EduStudentEnrollKindergarten formDetail = Convert.convert(EduStudentEnrollKindergarten.class, vo);
        EduSchoolVO eduSchoolVO=eduSchoolService.getDetail(vo.getSchoolId());
        vo.setAreaCode(eduSchoolVO.getAreaCode());
        // 判断是否有招生方案
        if (!eduSchoolVO.getHasEnrollFlag()&&!testFlag) {
            throw new AppException(year + "年度暂未制定招生方案，请拨打幼儿园电话了解详细情况");
        }
        int startBirthday = 0;
        int endBirthday = 0;
        List<EduSchoolConfigVO> configList = eduSchoolVO.getConfigList();
        EduSchoolConfigVO schoolConfig =null;
        Boolean fullFlag = false;
        Integer jhs = 0;
        if(!testFlag) {
            if (vo.getCheckEnrollTime()) {
                // 判断是否在操作期范围内
                //判断是否在年度招生时间中
                EduOperationCacheQueryVO queryVO=new EduOperationCacheQueryVO();
                queryVO.setClassify("1");
                queryVO.setAreaCode(vo.getAreaCode());
                queryVO.setYear(year);
                queryVO.setOperating("YRY001");
                EduOperationCacheDetailVO eduOperationCacheDetailVO=eduSystemConfigIntegration.getEduOperationOne(queryVO);
                if (eduOperationCacheDetailVO == null) {
                    throw new AppException(year + "年度幼儿园招生报名工作尚未开始");
                }
                if (!eduOperationCacheDetailVO.isFlag()) {
                    if ("1".equalsIgnoreCase(eduOperationCacheDetailVO.getType())) {
                        throw new AppException(year + "年度幼儿园招生报名工作尚未开始");
                    }
                    if ("2".equalsIgnoreCase(eduOperationCacheDetailVO.getType())) {
                        throw new AppException(year + "年度幼儿园招生报名工作已结束");
                    }
                    if ("3".equalsIgnoreCase(eduOperationCacheDetailVO.getType())) {
                        throw new AppException(year + "年度幼儿园招生报名工作尚未开始");
                    }
                }
            }else{
                //校验线下录入时间
                EduOperationCacheQueryVO queryVO=new EduOperationCacheQueryVO();
                queryVO.setClassify("1");
                queryVO.setAreaCode(vo.getAreaCode());
                queryVO.setYear(year);
                queryVO.setOperating("YRY005");
                EduOperationCacheVO eduOperationCacheVO=eduSystemConfigIntegration.getEduOperation(queryVO);
                if(eduOperationCacheVO==null){
                    throw new AppException("本年度幼儿园招生参数未配置，请联系系统管理员");
                }
                Map<String, EduOperationCacheDetailVO> operation=eduOperationCacheVO.getOperation();
                EduOperationCacheDetailVO xxOperation=operation.get("YRY005");
                if(xxOperation==null){
                    throw new AppException(vo.getYear()+"年度幼儿园学校线下报名录入工作尚未开始");
                }
                if(!xxOperation.isFlag()){
                    if ("1".equalsIgnoreCase(xxOperation.getType()) || "3".equalsIgnoreCase(xxOperation.getType())) {
                        throw new AppException(vo.getYear()+"年度幼儿园学校线下报名录入工作尚未开始");
                    }else{
                        throw new AppException(vo.getYear()+"年度幼儿园学校线下报名录入工作已结束");
                    }
                }
            }

            if(CollectionUtils.isEmpty(configList)){
                throw new AppException(year + "年度暂未制定该学段的招生计划，请拨打幼儿园电话了解详细情况");
            }
            for(EduSchoolConfigVO eduSchoolConfigVO:configList){
                if(eduSchoolConfigVO.getConfigType().equalsIgnoreCase(vo.getConfigType())){
                    schoolConfig=eduSchoolConfigVO;
                    break;
                }
            }
            if(schoolConfig==null){
                throw new AppException(year + "年度暂未制定该学段的招生计划，请拨打幼儿园电话了解详细情况");
            }
            if (schoolConfig.getStartTime() == null) {
                throw new AppException("招生计划中招生开始时间不能为空");
            }
            if (schoolConfig.getEndTime() == null) {
                throw new AppException("招生计划中招生结束时间不能为空");
            }
            if(vo.getCheckEnrollTime()){
                Long startTime = schoolConfig.getStartTime().getTime() / 1000;
                Long endTime = schoolConfig.getEndTime().getTime() / 1000;
                if (curDateTime < startTime) {
                    throw new AppException("本园招生未开始");
                }
                if (curDateTime > endTime) {
                    throw new AppException("本园招生已结束");
                }
            }
            if (schoolConfig.getStartAge() != null) {
                startBirthday =
                        Integer.parseInt(
                                DatePattern.PURE_DATE_FORMAT.format(schoolConfig.getStartAge()));
            }
            if (schoolConfig.getEndAge() != null) {
                endBirthday =
                        Integer.parseInt(
                                DatePattern.PURE_DATE_FORMAT.format(schoolConfig.getEndAge()));
            }

            if (BoolEnum.TRUE.getType().equalsIgnoreCase(schoolConfig.getFullFlag())) {
                fullFlag = true;
            }
            jhs = schoolConfig.getEnrolment();
            if(vo.getCheckAge()){
                String birthday = formDetail.getBirthYmd();
                if (birthday.length() == 8) {
                    // 针对出生日期填年月的兼容
                    Integer birth = Integer.parseInt(formDetail.getBirthYmd()) / 100;
                    if (startBirthday > 0) {
                        int startB = Integer.parseInt(String.valueOf(startBirthday).substring(0, 6));
                        if (birth < startB) {
                            throw new AppException("年龄不符");
                        }
                    }
                    if (endBirthday > 0) {
                        int endB = Integer.parseInt(String.valueOf(endBirthday).substring(0, 6));
                        if (birth > endB) {
                            throw new AppException("年龄不符");
                        }
                    }
                } else {
                    Integer birth = Integer.parseInt(formDetail.getBirthYmd());
                    if (startBirthday > 0 && birth < startBirthday) {
                        throw new AppException("年龄不符");
                    }
                    if (endBirthday > 0 && birth > endBirthday) {
                        throw new AppException("年龄不符");
                    }
                }
            }
        }

        formDetail.setSchoolId(vo.getSchoolId());
        if (CardTypeEnum.idcard.getType().equals(formDetail.getChildCardType())) {
            formDetail.setSex(
                    IdcardUtil.getGenderByIdCard(vo.getChildIdcard().toUpperCase()) == 0
                            ? "2"
                            : "1");
        } else {
            formDetail.setSex(vo.getSex());
        }

        int yearId = year % 100;
        String schoolCategoryId = "00";
        if (vo.getFormType().equals(EduFormTypeEnum.NURSERYENROLL.getType())) {
            schoolCategoryId = "0" + SchoolCategoryEnum.KINDERGARTEN.getType();
        }
        if(!testFlag) {
            Assert.hasText(formDetail.getFormId(), "表单id不能为空");
        }
        EduSchoolVO school = eduSchoolService.getDetail(vo.getSchoolId());
        Assert.notNull(school, "查询不到学校");
        formDetail.setAreaCode(school.getAreaCode());
        String schoolNum = StringUtils.leftPad(school.getSchoolNum() + "", 3, "0");
        String orderNoId = testFlag?"1":eduFormEnrollService.getById(formDetail.getFormId()).getOrderNo() + "";
        orderNoId = StringUtils.leftPad(orderNoId + "", 2, "0");

        //学校线下录入逻辑
        if (vo.getSource().equals("2")){
            //判断计划数和录取数
            QueryWrapper<EduStudentEnrollKindergarten> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(EduStudentEnrollKindergarten::getYear,vo.getYear())
                    .eq(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.lq.getType())
                    .eq(EduStudentEnrollKindergarten::getConfigType,vo.getConfigType())
                    .eq(EduStudentEnrollKindergarten::getSchoolId,vo.getSchoolId());
            long enrollStudentCount = eduStudentEnrollKindergartenService.count(queryWrapper);
            if (enrollStudentCount >= jhs){
                throw new AppException("学校线下录入的人数大于系统配置人数指标，无法进行学生录入，请联系教育局进行配置");
            }
            //判断当前学生在其他学校是否有待审核/待录取/录取
            List<String> enrollStatusList=new ArrayList<>();
            enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
            QueryWrapper<EduStudentEnrollKindergarten> otherQueryWrapper = new QueryWrapper<>();
            otherQueryWrapper.lambda().ne(EduStudentEnrollKindergarten::getSchoolId, formDetail.getSchoolId())
                    .eq(EduStudentEnrollKindergarten::getYear, vo.getYear())
                    .in(EduStudentEnrollKindergarten::getEnrollStatus, enrollStatusList)
                    .eq(EduStudentEnrollKindergarten::getChildIdcard, vo.getChildIdcard());
            if (eduStudentEnrollKindergartenService.count(otherQueryWrapper) > 0) {
                throw new AppException("该学生已在市内其他学校待审核/待录取/录取，不能直接录入，如有疑问，请联系管理员核对");
            }
            //查询该学校是否是待审核，待录取，已录取数据
            otherQueryWrapper.clear();
            otherQueryWrapper.lambda()
                    .eq(EduStudentEnrollKindergarten::getSchoolId,formDetail.getSchoolId())
                    .eq(EduStudentEnrollKindergarten::getYear,vo.getYear())
                    .eq(EduStudentEnrollKindergarten::getChildIdcard,vo.getChildIdcard())
                    .in(EduStudentEnrollKindergarten::getEnrollStatus,enrollStatusList);
            EduStudentEnrollKindergarten enrollKindergarten =
                            eduStudentEnrollKindergartenService.getOne(otherQueryWrapper, false);
            if (!ObjectUtils.isEmpty(enrollKindergarten)){
                //如果存在，判断是否为已录取状态
                if (EnrollStatusFormalEnum.lq.getType().equalsIgnoreCase(enrollKindergarten.getEnrollStatus())){
                    throw new AppException("该学生已是录取状态，请核对");
                }else {
                    //是待录取/待审核状态 需要进行录取
                    //先判断报名类别是否一致
                    if (!enrollKindergarten.getFormId().equalsIgnoreCase(formDetail.getFormId())){
                        //将信息进行拷贝过来
                        BeanUtils.copyProperties(enrollKindergarten,formDetail);
                        //不一致，需要重新生成
                        formDetail.setApplyId(null);
                    }else{
                        //如果招生类别一致，全部进行拷贝
                        BeanUtils.copyProperties(enrollKindergarten,formDetail);
                    }
                }
            }else{
                //本学校没有报名数据,生成报名id
                formDetail.setFormDetailId(IdUtil.simpleUUID());
            }
            //进行学生录入
            formDetail.setAuthRemarks("学校直接录入");
            formDetail.setAuthStatus(AuthStatusEnum.YES.getType());
            formDetail.setAdmitFlag(BoolEnum.TRUE.getType());
            formDetail.setAuthTime(new Date());
            formDetail.setEnrollStatus(EnrollStatusFormalEnum.lq.getType());
            formDetail.setAdmitRemarks(vo.getAdmitRemarks());
            formDetail.setSource("2");//学校线下录入
            saveFormDetail(formDetail, year, yearId, schoolCategoryId, schoolNum, orderNoId);
            vo.setApplyId(formDetail.getApplyId());
        }else{
            if (fullFlag) {
                //报满即止校验
                List<String> enrollList = new ArrayList<>();
                enrollList.add(EnrollStatusFormalEnum.hy.getType());
                enrollList.add(EnrollStatusFormalEnum.fs.getType());
                enrollList.add(EnrollStatusFormalEnum.dsh.getType());
                enrollList.add(EnrollStatusFormalEnum.dlq.getType());
                enrollList.add(EnrollStatusFormalEnum.lq.getType());
                QueryWrapper<EduStudentEnrollKindergarten> fullQuery = new QueryWrapper<>();
                fullQuery.lambda().eq(EduStudentEnrollKindergarten::getYear, year)
                        .eq(EduStudentEnrollKindergarten::getSchoolId, vo.getSchoolId())
                        .eq(EduStudentEnrollKindergarten::getConfigType, vo.getConfigType())
                        .in(EduStudentEnrollKindergarten::getEnrollStatus, enrollList);
                if (eduStudentEnrollKindergartenService.count(fullQuery) >= jhs) {
                    throw new AppException("该幼儿园报名名额已满，不能报名");
                }
            }
            if (!CollectionUtils.isEmpty(configList)) {
                //其他类型字段校验必填
                new ArrayList<>();
                Map<String,List<EduFormEnrollParamsVO>>  paramsMap=eduSchoolVO.getFormParams();
                List<EduFormEnrollParamsVO> paramsList = paramsMap.get(vo.getFormId());
                if(!CollectionUtils.isEmpty(paramsList)){
                    BeanWrapper beanWrapper = new BeanWrapperImpl(vo);
                    for (EduFormEnrollParamsVO config : paramsList) {
                        if (BoolEnum.TRUE.getType().equals(config.getRequiredFlag())) {
                            String param = config.getParam();
                            if (StringUtils.equals(config.getPropertyType(), "1") ||
                                    StringUtils.equals(config.getPropertyType(), "11") ||
                                    StringUtils.equals(config.getPropertyType(), "2") ||
                                    StringUtils.equals(config.getPropertyType(), "3")) {
                                if (StringUtils.isNotBlank(param) && beanWrapper.isWritableProperty(param)) {
                                    if (ObjectUtils.isEmpty(beanWrapper.getPropertyValue(param))) {
                                        throw new AppException(config.getProperty() + "必填");
                                    }
                                }
                            }
                        }
                    }
                }

            }

            QueryWrapper<EduStudentEnrollKindergarten> checkQueryWrapper = new QueryWrapper<>();
            checkQueryWrapper
                    .lambda()
                    .select(EduStudentEnrollKindergarten::getAuthStatus,EduStudentEnrollKindergarten::getEnrollStatus,EduStudentEnrollKindergarten::getAdmitFlag,EduStudentEnrollKindergarten::getSchoolId)
                    .eq(EduStudentEnrollKindergarten::getYear, year)
                    .eq(EduStudentEnrollKindergarten::getChildIdcard, vo.getChildIdcard());

            List<EduStudentEnrollKindergarten> oldEduFormDetailList = eduStudentEnrollKindergartenService.list(checkQueryWrapper);
            if (!CollectionUtils.isEmpty(oldEduFormDetailList)&&!testFlag) {
                // 如果存在多条记录，只要其中一条未审核或者待录入就提示不能申报
                for (EduStudentEnrollKindergarten oldForm : oldEduFormDetailList) {
                    if (StringUtils.isBlank(oldForm.getAuthStatus())
                            || StringUtils.isBlank(oldForm.getAdmitFlag())) {
                        throw new AppException("幼儿已申请，请前往申报记录查询！");
                    }
                    if (oldForm.getAuthStatus().equals(AuthStatusEnum.NODO.getType())) {
                        throw new AppException("幼儿已申请，请前往申报记录查询！");
                    }
                    if (oldForm.getSchoolId().equals(formDetail.getSchoolId())) {
                        if(AuthStatusEnum.NO.getType().equals(oldForm.getAuthStatus())){
                            throw new AppException("您之前报名过该学校，审核不通过，不能再次报名，如果有疑问请联系学校处理！");
                        }
                        throw new AppException("您之前报名过该学校，不能再次报名，如果有疑问请联系学校处理！");
                    }else{
                        if(AuthStatusEnum.YES.getType().equals(oldForm.getAuthStatus())&&BoolEnum.TRUE.getType().equalsIgnoreCase(oldForm.getAdmitFlag())){
                            throw new AppException("其他学校已录取，不能重新报名！");
                        }
                    }
                }
            }
            formDetail.setFormDetailId(IdUtil.simpleUUID());
            if(StringUtils.isBlank(formDetail.getAuthStatus())){
                formDetail.setAuthStatus(AuthStatusEnum.NODO.getType());
            }
            bindIdcardKindergarten(formDetail,vo.getBindIdcardList());
            // 调用同步锁保存方法
            saveFormDetail(formDetail, year, yearId, schoolCategoryId, schoolNum, orderNoId);
            vo.setApplyId(formDetail.getApplyId());


        }
        return vo;
    }

    //处理绑定摇号
    private void bindIdcardKindergarten(EduStudentEnrollKindergarten studentEnrollKindergarten, List<String> bindIdcardList){
        if(!BoolEnum.TRUE.getType().equalsIgnoreCase(studentEnrollKindergarten.getBindFlag())){
            return;
        }
        if(CollectionUtils.isEmpty(bindIdcardList)){
            throw new AppException("绑定的学生身份证不能为空");
        }
        if(ObjectUtils.isEmpty(studentEnrollKindergarten.getYear())){
            studentEnrollKindergarten.setYear(eduHelper.thisYear());
        }
        QueryWrapper<EduStudentEnrollKindergarten> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda()
                .in(EduStudentEnrollKindergarten::getChildIdcard,bindIdcardList)
                .eq(EduStudentEnrollKindergarten::getYear,studentEnrollKindergarten.getYear())
                .eq(EduStudentEnrollKindergarten::getSchoolId,studentEnrollKindergarten.getSchoolId())
                .eq(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.dsh.getType())
                .eq(EduStudentEnrollKindergarten::getConfigType,studentEnrollKindergarten.getConfigType())
                .orderByAsc(EduStudentEnrollKindergarten::getCreateTime,EduStudentEnrollKindergarten::getApplyId);
        List<EduStudentEnrollKindergarten> eduStudentEnrollKindergartens=eduStudentEnrollKindergartenService.list(queryWrapper);
        if(CollectionUtils.isEmpty(eduStudentEnrollKindergartens)){
            throw new AppException("未找到可绑定摇号的已报名学生信息，请退出重新报名");
        }
        int i=1;
        String bindIdcard="";
        for(EduStudentEnrollKindergarten enrollKindergarten:eduStudentEnrollKindergartens){
            if(i==1){
                bindIdcard=enrollKindergarten.getChildIdcard();
                if(!BoolEnum.TRUE.getType().equalsIgnoreCase(enrollKindergarten.getBindFlag())||!BoolEnum.TRUE.getType().equalsIgnoreCase(enrollKindergarten.getBindMianFlag())){
                    enrollKindergarten.setBindFlag(BoolEnum.TRUE.getType());
                    enrollKindergarten.setBindMianFlag(BoolEnum.TRUE.getType());
                    enrollKindergarten.setBindIdcard(bindIdcard);
                    eduStudentEnrollKindergartenService.updateById(enrollKindergarten);
                }
            }else{
                if(!BoolEnum.TRUE.getType().equalsIgnoreCase(enrollKindergarten.getBindFlag())||BoolEnum.TRUE.getType().equalsIgnoreCase(enrollKindergarten.getBindMianFlag())){
                    enrollKindergarten.setBindFlag(BoolEnum.TRUE.getType());
                    enrollKindergarten.setBindMianFlag(BoolEnum.FALSE.getType());
                    enrollKindergarten.setBindIdcard(bindIdcard);
                    eduStudentEnrollKindergartenService.updateById(enrollKindergarten);
                }
            }
            i=i+1;
        }
        studentEnrollKindergarten.setBindIdcard(bindIdcard);
        studentEnrollKindergarten.setBindMianFlag(BoolEnum.FALSE.getType());
    }

    @Override
    @OpApi(funcCode = "kindergarten0015", title = "幼儿园家长端报名", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "kindergarten0015",
            operationName = "幼儿园家长端报名",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    public EduStudentEnrollKindergartenVO addApp(EduStudentEnrollKindergartenVO vo) {
        vo.setSource("1");//家长报名
        vo.setCheckAge(true);
        vo.setCheckEnrollTime(true);
        return add(vo);
    }

    @Override
    @OpApi(funcCode = "kindergarten0017", title = "幼儿园报名管理端学校报名录入", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "kindergarten0017",
            operationName = "幼儿园报名管理端学校报名录入",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    public EduStudentEnrollKindergartenVO addBySchool(EduStudentEnrollKindergartenVO vo) {
        vo.setSource("2");//线下报名录入
        vo.setCheckAge(false);
        vo.setCheckEnrollTime(false);
        if(StringUtils.isBlank(vo.getSchoolId())){
            vo.setSchoolId(SessionUtil.getOrgId());
        }
        return add(vo);
    }

    @Override
    @OpApi(funcCode = "kindergarten0005", title = "幼儿园报名管理基本信息修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "kindergarten0005",
            operationName = "幼儿园报名管理基本信息修改",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduStudentEnrollKindergartenVO editBase(EduStudentEnrollKindergartenVO vo) {
        Boolean queryHistoryFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyQueryHistory(Integer.valueOf(vo.getYear()), handleTable));
        if (queryHistoryFlag) {
            throw new AppException("历史数据无法修改");
        }
        if (ObjectUtils.isEmpty(vo.getFormDetailId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        checkSave(vo);
        EduStudentEnrollKindergarten oldEntity = eduStudentEnrollKindergartenService.getById(vo.getFormDetailId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        int year = eduHelper.thisYear();
        if(oldEntity.getYear()<year){
            throw new AppException("历史数据不能操作");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduStudentEnrollKindergarten entity = Convert.convert(EduStudentEnrollKindergarten.class, vo);
        if("2".equals(entity.getAdmitFlag())){
            entity.setAdmitFlag(null);
        }
        eduStudentEnrollKindergartenService.updateById(entity);
        enrollClearCacheHelper.clearCacheMyEnroll(vo.getChildIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(vo.getFatherIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(vo.getMotherIdcard());
        return vo;
    }

    @Override
    @OpApi(funcCode = "kindergarten0006", title = "幼儿园报名管理根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "kindergarten0006",
            operationName = "幼儿园报名管理删除",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduStudentEnrollKindergartenKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getFormDetailId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduStudentEnrollKindergarten entity = eduStudentEnrollKindergartenService.getById(vo.getFormDetailId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        int year = eduHelper.thisYear();
        if(entity.getYear()<year){
            throw new AppException("历史数据不能操作");
        }
        eduStudentEnrollKindergartenService.removeById(vo.getFormDetailId());
        enrollClearCacheHelper.clearCacheMyEnroll(entity.getChildIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(entity.getFatherIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(entity.getMotherIdcard());
    }

    @Override
    @OpApi(funcCode = "kindergarten0007", title = "幼儿园报名管理-退回", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "kindergarten0007",
            operationName = "幼儿园报名管理-退回",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void nurseryFormBack(EduStudentEnrollKindergartenKeyVO vo) {
        EduStudentEnrollKindergarten detail = eduStudentEnrollKindergartenService.getById(vo.getFormDetailId());
        if(detail==null){
            throw new AppException("需要退回的数据不存在，请刷新");
        }
        if (!StringUtils.equals(detail.getAuthStatus(), AuthStatusEnum.NODO.getType())) {
            throw new AppException("当前人员已审核，不允许退回");
        }
        int year = eduHelper.thisYear();
        if(detail.getYear()<year){
            throw new AppException("历史数据不能操作");
        }
        EduSchoolVO eduSchoolVO=eduSchoolService.getDetail(detail.getSchoolId());
        boolean canFlag=false;
        if (!CollectionUtils.isEmpty(eduSchoolVO.getConfigList())) {
            long curTime = DateUtil.currentSeconds();
            for (EduSchoolConfigVO configVO : eduSchoolVO.getConfigList()) {
                if (configVO.getEndTime() != null && StringUtils.isNotBlank(configVO.getConfigType())) {
                    if (configVO.getConfigType().equals(detail.getConfigType())) {
                        long endT = configVO.getEndTime().getTime() / 1000;
                        if (curTime - endT <= 0) {
                            canFlag=true;
                        }
                    }
                }
            }
        }
        if (!canFlag){
            throw new AppException("已过报名时间，不能撤销报名");
        }
        eduStudentEnrollKindergartenService.removeById(vo.getFormDetailId());
        String bmKey = EduCache.EDU_ENROLL_KINDERGARTEN_ZS + detail.getChildIdcard();
        redisHelper.del(bmKey);
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getChildIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getFatherIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getMotherIdcard());
    }

    @Override
    @OpApi(funcCode = "kindergarten0008", title = "幼儿园报名管理根据身份证查询可退回人员", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentEnrollKindergartenVO> getNurseryFormInfoByIdcard(KindergartenIdcardQueryVO vo) {
        Assert.hasText(vo.getChildIdcard(), "身份证不能为空");
        int year = eduHelper.thisYear();
        QueryWrapper<EduStudentEnrollKindergarten> formDetailQueryWrapper = new QueryWrapper<>();
        formDetailQueryWrapper
                .lambda()
                .eq(EduStudentEnrollKindergarten::getYear, year)
                .eq(
                        !ObjectUtils.isEmpty(vo.getChildIdcard()),
                        EduStudentEnrollKindergarten::getChildIdcard,
                        vo.getChildIdcard())
                .eq(EduStudentEnrollKindergarten::getSchoolId, SessionUtil.getSessionInfo().getOrgId());

        List<EduStudentEnrollKindergarten> list = eduStudentEnrollKindergartenService.list(formDetailQueryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduStudentEnrollKindergarten> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduStudentEnrollKindergartenVO> resultList = Convert.toList(EduStudentEnrollKindergartenVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "kindergarten0009", title = "幼儿园报名管理-一键到待审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "kindergarten0009",
            operationName = "幼儿园报名管理-一键到待审核",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void nurseryBackAuth(EduStudentEnrollKindergartenKeyVO vo) {

        EduStudentEnrollKindergarten detail = eduStudentEnrollKindergartenService.getById(vo.getFormDetailId());
        if(detail==null){
            throw new AppException("报名数据不存在，请刷新");
        }
        if (StringUtils.equals(detail.getAuthStatus(), AuthStatusEnum.NODO.getType())) {
            throw new AppException("当前人员状态已经是待审核，请刷新");
        }
        int year = eduHelper.thisYear();
        if(detail.getYear()<year){
            throw new AppException("历史数据不能操作");
        }
        //如果其他学校待审核或录取，不能退回
        List<String> statusList=new ArrayList<>();
        statusList.add(EnrollStatusFormalEnum.hy.getType());
        statusList.add(EnrollStatusFormalEnum.fs.getType());
        statusList.add(EnrollStatusFormalEnum.dlq.getType());
        statusList.add(EnrollStatusFormalEnum.dsh.getType());
        statusList.add(EnrollStatusFormalEnum.lq.getType());
        LambdaQueryWrapper<EduStudentEnrollKindergarten> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.ne(EduStudentEnrollKindergarten::getSchoolId,detail.getSchoolId())
                .eq(EduStudentEnrollKindergarten::getChildIdcard,detail.getChildIdcard())
                .eq(EduStudentEnrollKindergarten::getYear, detail.getYear())
                .in(EduStudentEnrollKindergarten::getEnrollStatus,statusList);
        if(eduStudentEnrollKindergartenService.count(queryWrapper)>0){
            throw new AppException("其他学校待审核录取或者已录取,不能退回到审核状态");
        }
        detail.setAuthStatus(AuthStatusEnum.NODO.getType());
        detail.setAuthRemarks(null);
        detail.setAuthTime(null);
        detail.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
        detail.setAdmitFlag(null);
        detail.setAdmitRemarks(null);
        detail.setAdmitTime(null);
        eduStudentEnrollKindergartenService.updateById(detail);
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getChildIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getFatherIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getMotherIdcard());
    }

    @Override
    @OpApi(funcCode = "kindergarten0010", title = "幼儿园报名管理-设置报名无效", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "kindergarten0010",
            operationName = "幼儿园报名管理-设置报名无效",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void nurserySetStatus(EduStudentEnrollKindergartenKeyVO vo) {
        EduStudentEnrollKindergarten detail = eduStudentEnrollKindergartenService.getById(vo.getFormDetailId());
        if(detail==null){
            throw new AppException("报名数据不存在，请刷新");
        }
        if (StringUtils.equals(detail.getAuthStatus(), AuthStatusEnum.NODO.getType())) {
            throw new AppException("当前人员状态已经是待审核，请做退回操作");
        }
        int year = eduHelper.thisYear();
        if(detail.getYear()<year){
            throw new AppException("历史数据不能操作");
        }
        detail.setEnrollStatus(EnrollStatusFormalEnum.xtblq.getType());
        eduStudentEnrollKindergartenService.updateById(detail);
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getChildIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getFatherIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getMotherIdcard());
    }

    @Override
    @OpApi(funcCode = "kindergarten0011", title = "幼儿园报名管理-审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "kindergarten0011",
            operationName = "幼儿园报名管理-审核",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void auth(EduStudentEnrollKindergartenAuthVO vo) {
        String formDetailId = vo.getFormDetailId();
        String authStatus = vo.getAuthStatus();

        Assert.hasText(formDetailId, "表单明细id不能为空");
        Assert.hasText(authStatus, "审核状态不能为空");
        EduStudentEnrollKindergarten formDetail = eduStudentEnrollKindergartenService.getById(vo.getFormDetailId());
        Assert.notNull(formDetail, "查询不到报名信息");
        int year = eduHelper.thisYear();
        if(formDetail.getYear()<year){
            throw new AppException("历史数据不能操作");
        }
        if (AuthStatusEnum.YES.getType().equals(formDetail.getAuthStatus())
                || AuthStatusEnum.NO.getType().equals(formDetail.getAuthStatus())) {
            throw new AppException("该业务已被审核，请刷新核对");
        }

        QueryWrapper<EduStudentEnrollKindergarten> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduStudentEnrollKindergarten::getChildIdcard,formDetail.getChildIdcard())
                .eq(EduStudentEnrollKindergarten::getAuthStatus,AuthStatusEnum.YES.getType())
                .eq(EduStudentEnrollKindergarten::getAdmitFlag,BoolEnum.TRUE.getType())
                .eq(EduStudentEnrollKindergarten::getYear,year)
                .ne(EduStudentEnrollKindergarten::getSchoolId,formDetail.getSchoolId());
        if(eduStudentEnrollKindergartenService.count(queryWrapper)>0){
            throw new AppException("该幼儿已被其他学校录取，不能审核");
        }
        if (AuthStatusEnum.NO.getType().equals(vo.getAuthStatus())) {
            formDetail.setAdmitFlag(BoolEnum.FALSE.getType());
            formDetail.setAdmitTime(new Date());
            formDetail.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
            formDetail.setAdmitRemarks("审核不通过.");
        } else if (AuthStatusEnum.YES.getType().equals(vo.getAuthStatus())) {
            formDetail.setEnrollStatus(EnrollStatusFormalEnum.dlq.getType());
        }

        formDetail.setAuthStatus(authStatus);
        formDetail.setAuthRemarks(vo.getAuthRemarks());
        formDetail.setAuthTime(new Date());

        eduStudentEnrollKindergartenService.updateById(formDetail);
        enrollClearCacheHelper.clearCacheMyEnroll(formDetail.getChildIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(formDetail.getFatherIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(formDetail.getMotherIdcard());
    }

    @Override
    @OpApi(funcCode = "kindergarten0012", title = "幼儿园报名管理-单个录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "kindergarten0012",
            operationName = "幼儿园报名管理-单个录取",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void admit(EduStudentEnrollKindergartenAdmitVO vo) {
        String formDetailId = vo.getFormDetailId();
        Assert.hasText(formDetailId, "报名id不能为空");
        if (StringUtils.isBlank(vo.getAdmitFlag())){
            throw new AppException("录取状态不能为空");
        }
        EduStudentEnrollKindergarten detail = eduStudentEnrollKindergartenService.getById(formDetailId);
        Assert.notNull(detail, "查询不到报名信息");
        int year = eduHelper.thisYear();
        if(detail.getYear()<year){
            throw new AppException("历史数据不能操作");
        }
        if (!AuthStatusEnum.YES.getType().equalsIgnoreCase(detail.getAuthStatus())) {
            throw new AppException("该学生审核不通过，不能录取");
        }
        if (StringUtils.isNotBlank(detail.getAdmitFlag())) {
            throw new AppException("该学生已办理录取操作，请刷新核对");
        }
        if(BoolEnum.TRUE.getType().equalsIgnoreCase(vo.getAdmitFlag())){
            //判断录取人数是否大于计划招生人数
            Integer enrolment=getJhs(detail.getSchoolId(),detail.getConfigType(),year);
            //获取已录取人数
            Long lqrs=getLqrs(detail.getSchoolId(),detail.getConfigType(),detail.getYear());
            if(lqrs-enrolment>=0){
                throw new AppException("录取人数已超过计划数，不能录取，如需修改计划数，请联系教育局相关工作人员");
            }
        }

        if ("1".equals(vo.getAdmitFlag())) {
            detail.setEnrollStatus(EnrollStatusFormalEnum.lq.getType());
        } else {
            detail.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
        }

        detail.setAdmitFlag(vo.getAdmitFlag());
        detail.setAdmitTime(new Date());
        detail.setAdmitRemarks(vo.getAdmitRemarks());
//        detail.setEnrollStatus(EnrollStatusFormalEnum.lq.getType());
        eduStudentEnrollKindergartenService.updateById(detail);
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getChildIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getFatherIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getMotherIdcard());
    }
    //获取已录取人数
    private Long getLqrs(String schoolId,String configType,Integer year){
        LambdaQueryWrapper<EduStudentEnrollKindergarten> lqQuery=new LambdaQueryWrapper<>();
        lqQuery.eq(EduStudentEnrollKindergarten::getAdmitFlag,BoolEnum.TRUE.getType())
                .eq(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.lq.getType())
                .eq(EduStudentEnrollKindergarten::getAuthStatus,AuthStatusEnum.YES.getType())
                .eq(EduStudentEnrollKindergarten::getSchoolId,schoolId)
                .eq(EduStudentEnrollKindergarten::getYear,year)
                .eq(EduStudentEnrollKindergarten::getConfigType,configType);
        return eduStudentEnrollKindergartenService.count(lqQuery);
    }
    private Integer getJhs(String schoolId,String configType,Integer year){
        LambdaQueryWrapper<EduSchoolConfig> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.select(EduSchoolConfig::getEnrolment).eq(EduSchoolConfig::getYear,year)
                .eq(EduSchoolConfig::getSchoolId,schoolId)
                .eq(EduSchoolConfig::getConfigType,configType)
                .eq(EduSchoolConfig::getStatus,BoolEnum.TRUE.getType())
                .eq(EduSchoolConfig::getAuthStatus,AuthStatusEnum.YES.getType());
        EduSchoolConfig eduSchoolConfig=eduSchoolConfigService.getOne(queryWrapper,false);
        Integer enrolment=null;
        if(eduSchoolConfig!=null){
            enrolment=eduSchoolConfig.getEnrolment();
        }
        if(enrolment==null){
            throw new AppException("该录取学段计划招生人数未配置");
        }
        return enrolment;
    }
    @Override
    @OpApi(funcCode = "kindergarten0013", title = "幼儿园报名管理-一键录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "kindergarten0013",
            operationName = "幼儿园报名管理-一键录取",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void admitBatch(EduStudentEnrollKindergartenAdmitVO vo) {
        if(StringUtils.isBlank(vo.getConfigType())){
            throw new AppException("录取的学段不能为空");
        }

        int year=eduHelper.thisYear();
        String schoolId=SessionUtil.getOrgId();
        if(StringUtils.isBlank(schoolId)){
            throw new AppException("用户所属组织不能为空");
        }
        EduSchoolVO eduSchoolVO=eduSchoolService.getDetail(schoolId);
        if(eduSchoolVO==null){
            throw new AppException("该功能只能学校账号操作");
        }
        //判断录取人数是否大于计划招生人数
        Integer enrolment=getJhs(schoolId,vo.getConfigType(),year);
        //获取已录取人数
        Long lqrs=getLqrs(schoolId,vo.getConfigType(),year);
        //获取待录取人数
        LambdaQueryWrapper<EduStudentEnrollKindergarten> lqQuery=new LambdaQueryWrapper<>();
        lqQuery.eq(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.dlq.getType())
                .eq(EduStudentEnrollKindergarten::getAuthStatus,AuthStatusEnum.YES.getType())
                .eq(EduStudentEnrollKindergarten::getSchoolId,schoolId)
                .eq(EduStudentEnrollKindergarten::getConfigType,vo.getConfigType());
        Long dlq=eduStudentEnrollKindergartenService.count(lqQuery);
        if(lqrs+dlq-enrolment>0){
            throw new AppException("录取人数已超过计划数，不能一键录取，如需修改计划数，请联系教育局相关工作人员");
        }
        QueryWrapper<EduStudentEnrollKindergarten> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().select(EduStudentEnrollKindergarten::getChildIdcard,EduStudentEnrollKindergarten::getFatherIdcard,EduStudentEnrollKindergarten::getMotherIdcard).eq(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.dlq.getType())
                .eq(EduStudentEnrollKindergarten::getAuthStatus,AuthStatusEnum.YES.getType())
                .eq(EduStudentEnrollKindergarten::getSchoolId,schoolId)
                .eq(EduStudentEnrollKindergarten::getConfigType,vo.getConfigType());
        List<EduStudentEnrollKindergarten> kindergartens=eduStudentEnrollKindergartenService.list(queryWrapper);
        if(CollectionUtils.isEmpty(kindergartens)){
            return;
        }
        for(EduStudentEnrollKindergarten detail:kindergartens){
            enrollClearCacheHelper.clearCacheMyEnroll(detail.getChildIdcard());
            enrollClearCacheHelper.clearCacheMyEnroll(detail.getFatherIdcard());
            enrollClearCacheHelper.clearCacheMyEnroll(detail.getMotherIdcard());
        }
        UpdateWrapper<EduStudentEnrollKindergarten> updateWrapper=new UpdateWrapper<>();
        updateWrapper.lambda().eq(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.dlq.getType())
                .eq(EduStudentEnrollKindergarten::getAuthStatus,AuthStatusEnum.YES.getType())
                .eq(EduStudentEnrollKindergarten::getSchoolId,schoolId)
                .eq(EduStudentEnrollKindergarten::getConfigType,vo.getConfigType())
                .set(EduStudentEnrollKindergarten::getAdmitFlag,BoolEnum.TRUE.getType())
                .set(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.lq.getType())
                .set(EduStudentEnrollKindergarten::getAdmitRemarks,vo.getAdmitRemarks())
                .set(EduStudentEnrollKindergarten::getAdmitTime,new Date());
        eduStudentEnrollKindergartenService.update(updateWrapper);
    }

    @Override
    @OpApi(funcCode = "kindergarten0014", title = "幼儿园报名管理-退回数据重新补录", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "kindergarten0014",
            operationName = "幼儿园报名管理-退回数据重新补录",
            dataType = "formDetailId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void backDel(EduStudentEnrollKindergartenVO vo) {

        if(StringUtils.isBlank(vo.getChildIdcard())){
            throw new AppException("幼儿证件号码不能为空");
        }
        if(StringUtils.isBlank(vo.getConfigType())){
            throw new AppException("学段不能为空");
        }
        int year = eduHelper.thisYear();

        if(StringUtils.isBlank(vo.getSchoolId())){
            vo.setSchoolId(SessionUtil.getOrgId());
        }
        String areaCode=vo.getAreaCode();
        if(StringUtils.isBlank(areaCode)){
            areaCode=SessionUtil.getAreaCode();
        }
        String schoolId=vo.getSchoolId();
        List<String> statusList=new ArrayList<>();
        statusList.add(EnrollStatusFormalEnum.hy.getType());
        statusList.add(EnrollStatusFormalEnum.fs.getType());
        statusList.add(EnrollStatusFormalEnum.dlq.getType());
        statusList.add(EnrollStatusFormalEnum.dsh.getType());
        statusList.add(EnrollStatusFormalEnum.lq.getType());
        LambdaQueryWrapper<EduStudentEnrollKindergarten> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduStudentEnrollKindergarten::getChildIdcard,vo.getChildIdcard())
                .in(EduStudentEnrollKindergarten::getEnrollStatus,statusList)
                .eq(EduStudentEnrollKindergarten::getAreaCode,areaCode);
        if(eduStudentEnrollKindergartenService.count(queryWrapper)>0){
            throw new AppException("该学生处于待审核录取或者已录取,不能补录");
        }

        QueryWrapper<EduSchoolConfig> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper
                .lambda()
                .eq(EduSchoolConfig::getSchoolId, schoolId)
                .eq(EduSchoolConfig::getYear, year)
                .eq(EduSchoolConfig::getStatus, BoolEnum.TRUE.getType())
                .eq(EduSchoolConfig::getAuthStatus, AuthStatusEnum.YES.getType())
                .eq(EduSchoolConfig::getConfigType, vo.getConfigType());
        List<EduSchoolConfig> configList = eduSchoolConfigService.list(configQueryWrapper);
        if(CollectionUtils.isEmpty(configList)){
            throw new AppException("不存在该学段招生计划");
        }
        List<EduStudentEnrollKindergarten> oldList=eduStudentEnrollKindergartenService.queryDelByIdcard(vo.getChildIdcard(),null,areaCode);
        if (CollectionUtils.isEmpty(oldList)){
            throw new AppException("该学生没有报名或者不是退回状态，不能补录");
        }
        EduStudentEnrollKindergarten old=oldList.get(0);
        for(EduStudentEnrollKindergarten eduStudentEnrollKindergarten:oldList){
            old=eduStudentEnrollKindergarten;
            if (eduStudentEnrollKindergarten.getSchoolId().equalsIgnoreCase(schoolId)){
                old.setApplyId(null);
                break;
            }
        }
        vo.setFormType("1");
        if(StringUtils.isBlank(vo.getFormType())){
            throw new AppException("学段（幼儿班、小学、初中）不能为空");
        }
        int yearId = year % 100;
        String schoolCategoryId = "00";
        if (vo.getFormType().equals(EduFormTypeEnum.NURSERYENROLL.getType())) {
            schoolCategoryId = "0" + SchoolCategoryEnum.KINDERGARTEN.getType();
        }
        Assert.hasText(old.getFormId(), "表单id不能为空");
        EduSchoolVO school = eduSchoolService.getDetail(schoolId);
        Assert.notNull(school, "查询不到学校");
        String schoolNum = StringUtils.leftPad(school.getSchoolNum() + "", 3, "0");
        String orderNoId = eduFormEnrollService.getById(old.getFormId()).getOrderNo() + "";
        orderNoId = StringUtils.leftPad(orderNoId + "", 2, "0");
        EduStudentEnrollKindergarten eduFormDetail=Convert.convert(EduStudentEnrollKindergarten.class,old);
        eduFormDetail.setConfigType(vo.getConfigType());
        eduFormDetail.setConfigName(vo.getConfigName());
        eduFormDetail.setFormId(old.getFormId());
        eduFormDetail.setSchoolId(schoolId);
        eduFormDetail.setFormDetailId(IdUtil.simpleUUID());
        eduFormDetail.setAuthTime(null);
        eduFormDetail.setAuthStatus(AuthStatusEnum.NODO.getType());
        eduFormDetail.setAuthRemarks(null);
        eduFormDetail.setAdmitFlag(null);
        eduFormDetail.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
        eduFormDetail.setAdmitTime(null);
        eduFormDetail.setAdmitRemarks(null);
        saveFormDetail(eduFormDetail, year, yearId, schoolCategoryId, schoolNum, orderNoId);

    }

    @Override
    @OpApi(funcCode = "kindergarten0016", title = "幼儿园报名管理-excel数据导出", funcType = FuncTypeEnum.other)
    public void downloadData(EduStudentEnrollKindergartenQueryVO vo, HttpServletResponse response) {
        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode("nurseryApplyInfo");
        ExcelModelVO excelModelVO=excelIntegration.getModel(excelVO);

        String destFilePath = this.tempPath + "/" + IdUtil.fastSimpleUUID() + "." + excelModelVO.getExcelType();
        int pageNum=1;
        setData(excelModelVO,null,destFilePath,vo,pageNum);
        String fileName="幼儿园报名数据"+DateUtil.today();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }
        File file = FileUtil.file(destFilePath);
        BufferedInputStream in = null;
        try {
            in = FileUtil.getInputStream(file);
            ServletUtil.write(response, in, "application/octet-stream;charset=utf-8", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.del(destFilePath);
        }
    }


    @Override
    @OpApi(funcCode = "kindergarten0018", title = "幼儿园房产比对查询", funcType = FuncTypeEnum.query)
    public PageInfo<KindergartenCompareVO> getNurseryHouseCompareData(KindergartenCompareVO vo) {
        if (ObjectUtils.isEmpty(vo.getOrgId())) {
            vo.setOrgId(SessionUtil.getSessionInfo().getOrgId());
        }
        if (ObjectUtils.isEmpty(vo.getYear())) {
            vo.setYear(eduHelper.thisYear());
        }

        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());

        QueryWrapper<EduStudentEnrollKindergarten> kindergartenQueryWrapper = new QueryWrapper<>();
        kindergartenQueryWrapper.lambda()
                .eq(StringUtils.isNotBlank(vo.getChildIdcard()), EduStudentEnrollKindergarten::getChildIdcard, vo.getChildIdcard())
                .eq(EduStudentEnrollKindergarten::getSchoolId, vo.getOrgId())
                .eq(EduStudentEnrollKindergarten::getYear, vo.getYear());

        List<EduStudentEnrollKindergarten> kindergartenList = eduStudentEnrollKindergartenService.list(kindergartenQueryWrapper);

        List<String> idcardList = new ArrayList<>();
        List<String> fatherIdcardList = new ArrayList<>();
        List<String> motherIdcardList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(kindergartenList)) {
            fatherIdcardList = kindergartenList.stream().map(EduStudentEnrollKindergarten::getFatherIdcard).distinct().collect(Collectors.toList());
            motherIdcardList = kindergartenList.stream().map(EduStudentEnrollKindergarten::getMotherIdcard).distinct().collect(Collectors.toList());
            idcardList = Stream.of(fatherIdcardList, motherIdcardList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
        } else {
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }

        PageInfo<EduStudentEnrollKindergarten> pageInfo = new PageInfo<>(kindergartenList);

        List<KindergartenCompareVO> resultList = Convert.toList(KindergartenCompareVO.class, pageInfo.getList());

        vo.setIdcardList(idcardList);
        List<KindergartenCompareVO> compareVOList = eduStudentEnrollKindergartenService.getNurseryHouseCompareData(vo);
        Map<String, KindergartenCompareVO> houseNurseryMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(compareVOList)) {
            houseNurseryMap = compareVOList.stream().collect(Collectors.toMap(KindergartenCompareVO::getIdcard, a -> a, (k1, k2) -> k1));
            for (KindergartenCompareVO compareVO : resultList) {
                if (houseNurseryMap.get(compareVO.getFatherIdcard()) != null) {
                    compareVO.setHouseId(houseNurseryMap.get(compareVO.getFatherIdcard()).getHouseId());
                    compareVO.setFcAddress(houseNurseryMap.get(compareVO.getFatherIdcard()).getAddress());
                    compareVO.setRegisterDate(houseNurseryMap.get(compareVO.getFatherIdcard()).getRegisterDate());
                    compareVO.setRealProperty(houseNurseryMap.get(compareVO.getFatherIdcard()).getRealProperty());
                    compareVO.setRealPropertyNum(houseNurseryMap.get(compareVO.getFatherIdcard()).getRealPropertyNum());
                    compareVO.setBegDate(houseNurseryMap.get(compareVO.getFatherIdcard()).getBegDate());
                    compareVO.setEndDate(houseNurseryMap.get(compareVO.getFatherIdcard()).getEndDate());
                    compareVO.setYearLimit(houseNurseryMap.get(compareVO.getFatherIdcard()).getYearLimit());
                    compareVO.setLandCategories(houseNurseryMap.get(compareVO.getFatherIdcard()).getLandCategories());
                    compareVO.setLandCategoriesName(houseNurseryMap.get(compareVO.getFatherIdcard()).getLandCategoriesName());
                    compareVO.setHouseNature(houseNurseryMap.get(compareVO.getFatherIdcard()).getHouseNature());
                    compareVO.setHouseNatureName(houseNurseryMap.get(compareVO.getFatherIdcard()).getHouseNatureName());
                    compareVO.setQlrName(houseNurseryMap.get(compareVO.getFatherIdcard()).getQlrName());
                    compareVO.setFcAddress(houseNurseryMap.get(compareVO.getFatherIdcard()).getFcAddress());
                }
                if (houseNurseryMap.get(compareVO.getMotherIdcard()) != null) {
                    compareVO.setHouseId(houseNurseryMap.get(compareVO.getMotherIdcard()).getHouseId());
                    compareVO.setFcAddress(houseNurseryMap.get(compareVO.getMotherIdcard()).getAddress());
                    compareVO.setRegisterDate(houseNurseryMap.get(compareVO.getMotherIdcard()).getRegisterDate());
                    compareVO.setRealProperty(houseNurseryMap.get(compareVO.getMotherIdcard()).getRealProperty());
                    compareVO.setRealPropertyNum(houseNurseryMap.get(compareVO.getMotherIdcard()).getRealPropertyNum());
                    compareVO.setBegDate(houseNurseryMap.get(compareVO.getMotherIdcard()).getBegDate());
                    compareVO.setEndDate(houseNurseryMap.get(compareVO.getMotherIdcard()).getEndDate());
                    compareVO.setYearLimit(houseNurseryMap.get(compareVO.getMotherIdcard()).getYearLimit());
                    compareVO.setLandCategories(houseNurseryMap.get(compareVO.getMotherIdcard()).getLandCategories());
                    compareVO.setLandCategoriesName(houseNurseryMap.get(compareVO.getMotherIdcard()).getLandCategoriesName());
                    compareVO.setHouseNature(houseNurseryMap.get(compareVO.getMotherIdcard()).getHouseNature());
                    compareVO.setHouseNatureName(houseNurseryMap.get(compareVO.getMotherIdcard()).getHouseNatureName());
                    compareVO.setQlrName(houseNurseryMap.get(compareVO.getMotherIdcard()).getQlrName());
                    compareVO.setFcAddress(houseNurseryMap.get(compareVO.getMotherIdcard()).getFcAddress());
                }
            }
        }

        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(EduEnrollKindergartenDictEnum.values()));

        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "kindergarten0019", title = "幼儿园户籍比对查询", funcType = FuncTypeEnum.query)
    public PageInfo<KindergartenCompareVO> getNurseryHouseHoldCompareData(KindergartenCompareVO vo) {
        if (ObjectUtils.isEmpty(vo.getOrgId())) {
            vo.setOrgId(SessionUtil.getSessionInfo().getOrgId());
        }
        if(ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }

        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());

        List<KindergartenCompareVO> list = eduStudentEnrollKindergartenService.getNurseryHouseHoldCompareData(vo);

        PageInfo<KindergartenCompareVO> pageInfo = new PageInfo<>(list);

        List<KindergartenCompareVO> resultList = Convert.toList(KindergartenCompareVO.class, pageInfo.getList());

        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(SchoolConfigDictEnum.values()));
        dictHelper.valueToName(resultList, Arrays.asList(EduEnrollKindergartenDictEnum.values()));

        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "kindergarten0020", title = "幼儿园房产户籍比对", funcType = FuncTypeEnum.edit)
    @Async("commonTaskExecutor")
    public void nurseryDataCompare(KindergartenCompareVO vo) {
        String orgId = SessionUtil.getSessionInfo().getOrgId();
        String checkRedisKey = "HD_" + orgId;

        if (redisHelper.hasKey(checkRedisKey)) {
            throw new AppException("正在比对，请稍后");
        }else {
            redisHelper.set(checkRedisKey, "1");
        }
        int year = 0;
        year = eduHelper.thisYear();

        QueryWrapper<EduStudentEnrollKindergarten> detailQueryWrapper = new QueryWrapper<>();
        detailQueryWrapper
                .lambda()
                .eq(EduStudentEnrollKindergarten::getSchoolId, orgId)
                .eq(EduStudentEnrollKindergarten::getYear, year);
        List<EduStudentEnrollKindergarten> detailList = eduStudentEnrollKindergartenService.list(detailQueryWrapper);
        if (StringUtils.equals(vo.getCompareFlag(), BoolEnum.TRUE.getType())) {
            detailList =
                    detailList.stream()
                            .filter(
                                    item ->
                                            StringUtils.equals(
                                                    item.getHouseholdSyncFlag(),
                                                    BoolEnum.FALSE.getType()))
                            .collect(Collectors.toList());
        }
        detailList.forEach(
                item -> {
                    HouseHoldSaveVO saveVO = new HouseHoldSaveVO();
                    saveVO.setIdcard(item.getChildIdcard());
                    saveVO.setReqIp(vo.getReqIp());
                    try {
                        eduHouseholdIntegration.saveHouseHoldData(saveVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                    saveVO.setIdcard(item.getFatherIdcard());
                    saveVO.setReqIp(vo.getReqIp());
                    try {
                        eduHouseholdIntegration.saveHouseHoldData(saveVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                    saveVO.setIdcard(item.getMotherIdcard());
                    try {
                        eduHouseholdIntegration.saveHouseHoldData(saveVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                    EduStudentEnrollKindergarten detail = eduStudentEnrollKindergartenService.getById(item.getFormDetailId());
                    detail.setHouseholdSyncFlag(BoolEnum.TRUE.getType());
                    detail.setHouseholdSyncRemark("调用成功");
                    eduStudentEnrollKindergartenService.updateById(detail);
                });
        detailList.forEach(
                item -> {
                    HouseInterfaceSaveVO saveVO = new HouseInterfaceSaveVO();
                    List<String> allIdcardList = new ArrayList<>();
                    allIdcardList.add(item.getChildIdcard());
                    if (!ObjectUtils.isEmpty(item.getFatherIdcard())) {
                        allIdcardList.add(item.getFatherIdcard());
                    }
                    if (!ObjectUtils.isEmpty(item.getMotherIdcard())) {
                        allIdcardList.add(item.getMotherIdcard());
                    }
                    saveVO.setIdcard(item.getChildIdcard());
                    saveVO.setName(item.getChildFullName());
                    saveVO.setAllIdcardList(allIdcardList);
                    try {
                        eduHouseIntegration.saveHouseNurseryInterfaceData(saveVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }
                    if (!ObjectUtils.isEmpty(item.getFatherIdcard())) {
                        saveVO.setIdcard(item.getFatherIdcard());
                        saveVO.setName(item.getFatherName());
                        saveVO.setAllIdcardList(allIdcardList);
                        try {
                            eduHouseIntegration.saveHouseNurseryInterfaceData(saveVO);
                        } catch (Exception e) {
                            e.printStackTrace();
                            return;
                        }
                    }
                    if (!ObjectUtils.isEmpty(item.getMotherIdcard())) {
                        saveVO.setIdcard(item.getMotherIdcard());
                        saveVO.setName(item.getMotherName());
                        saveVO.setAllIdcardList(allIdcardList);
                        try {
                            eduHouseIntegration.saveHouseNurseryInterfaceData(saveVO);
                        } catch (Exception e) {
                            e.printStackTrace();
                            return;
                        }
                    }
                    EduStudentEnrollKindergarten detail = eduStudentEnrollKindergartenService.getById(item.getFormDetailId());
                    detail.setHouseSyncFlag(BoolEnum.TRUE.getType());
                    detail.setHouseSyncRemark("调用成功");
                    eduStudentEnrollKindergartenService.updateById(detail);
                });
        redisHelper.del(checkRedisKey);

    }


    @Override
    @OpApi(funcCode = "kindergarten0021", title = "幼儿园房产和户籍比对查询", funcType = FuncTypeEnum.query)
    public PageInfo<KindergartenCompareVO> getNurseryHouseAndHouseHoldCompareData(KindergartenCompareVO vo) {
        if (ObjectUtils.isEmpty(vo.getOrgId())) {
            vo.setOrgId(SessionUtil.getSessionInfo().getOrgId());
        }
        if (ObjectUtils.isEmpty(vo.getYear())) {
            vo.setYear(eduHelper.thisYear());
        }

        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());

        QueryWrapper<EduStudentEnrollKindergarten> kindergartenQueryWrapper = new QueryWrapper<>();
        kindergartenQueryWrapper.lambda()
                .eq(StringUtils.isNotBlank(vo.getChildIdcard()), EduStudentEnrollKindergarten::getChildIdcard, vo.getChildIdcard())
                .eq(EduStudentEnrollKindergarten::getSchoolId, vo.getOrgId())
                .eq(EduStudentEnrollKindergarten::getYear, vo.getYear());

        List<EduStudentEnrollKindergarten> kindergartenList = eduStudentEnrollKindergartenService.list(kindergartenQueryWrapper);

        List<String> idcardList = new ArrayList<>();
        List<String> childIdcardList = new ArrayList<>();
        List<String> fatherIdcardList = new ArrayList<>();
        List<String> motherIdcardList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(kindergartenList)) {
            childIdcardList =  kindergartenList.stream().map(EduStudentEnrollKindergarten::getChildIdcard).distinct().collect(Collectors.toList());
            fatherIdcardList = kindergartenList.stream().map(EduStudentEnrollKindergarten::getFatherIdcard).distinct().collect(Collectors.toList());
            motherIdcardList = kindergartenList.stream().map(EduStudentEnrollKindergarten::getMotherIdcard).distinct().collect(Collectors.toList());
            idcardList = Stream.of(fatherIdcardList, motherIdcardList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
        } else {
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }

        PageInfo<EduStudentEnrollKindergarten> pageInfo = new PageInfo<>(kindergartenList);

        List<KindergartenCompareVO> resultList = Convert.toList(KindergartenCompareVO.class, pageInfo.getList());

        vo.setIdcardList(idcardList);
        vo.setChildIdcardList(childIdcardList);
        List<KindergartenCompareVO> compareVOList = eduStudentEnrollKindergartenService.getNurseryHouseCompareData(vo);
        List<KindergartenCompareVO> householdVOList = eduStudentEnrollKindergartenService.getNurseryHouseHoldCompareData(vo);



        Map<String, KindergartenCompareVO> houseNurseryMap = new HashMap<>();
        Map<String,KindergartenCompareVO> householdMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(compareVOList)) {
            houseNurseryMap = compareVOList.stream().collect(Collectors.toMap(KindergartenCompareVO::getIdcard, a -> a, (k1, k2) -> k1));
            householdMap = householdVOList.stream().collect(Collectors.toMap(KindergartenCompareVO::getChildIdcard, a -> a, (k1, k2) -> k1));
            for (KindergartenCompareVO compareVO : resultList) {
                //房产信息
                if (houseNurseryMap.get(compareVO.getFatherIdcard()) != null) {
                    compareVO.setHouseId(houseNurseryMap.get(compareVO.getFatherIdcard()).getHouseId());
                    compareVO.setFcAddress(houseNurseryMap.get(compareVO.getFatherIdcard()).getAddress());
                    compareVO.setRegisterDate(houseNurseryMap.get(compareVO.getFatherIdcard()).getRegisterDate());
                    compareVO.setRealProperty(houseNurseryMap.get(compareVO.getFatherIdcard()).getRealProperty());
                    compareVO.setRealPropertyNum(houseNurseryMap.get(compareVO.getFatherIdcard()).getRealPropertyNum());
                    compareVO.setBegDate(houseNurseryMap.get(compareVO.getFatherIdcard()).getBegDate());
                    compareVO.setEndDate(houseNurseryMap.get(compareVO.getFatherIdcard()).getEndDate());
                    compareVO.setYearLimit(houseNurseryMap.get(compareVO.getFatherIdcard()).getYearLimit());
                    compareVO.setLandCategories(houseNurseryMap.get(compareVO.getFatherIdcard()).getLandCategories());
                    compareVO.setLandCategoriesName(houseNurseryMap.get(compareVO.getFatherIdcard()).getLandCategoriesName());
                    compareVO.setHouseNature(houseNurseryMap.get(compareVO.getFatherIdcard()).getHouseNature());
                    compareVO.setHouseNatureName(houseNurseryMap.get(compareVO.getFatherIdcard()).getHouseNatureName());
                    compareVO.setQlrName(houseNurseryMap.get(compareVO.getFatherIdcard()).getQlrName());
                    compareVO.setFcAddress(houseNurseryMap.get(compareVO.getFatherIdcard()).getFcAddress());
                }
                if (houseNurseryMap.get(compareVO.getMotherIdcard()) != null) {
                    compareVO.setHouseId(houseNurseryMap.get(compareVO.getMotherIdcard()).getHouseId());
                    compareVO.setFcAddress(houseNurseryMap.get(compareVO.getMotherIdcard()).getAddress());
                    compareVO.setRegisterDate(houseNurseryMap.get(compareVO.getMotherIdcard()).getRegisterDate());
                    compareVO.setRealProperty(houseNurseryMap.get(compareVO.getMotherIdcard()).getRealProperty());
                    compareVO.setRealPropertyNum(houseNurseryMap.get(compareVO.getMotherIdcard()).getRealPropertyNum());
                    compareVO.setBegDate(houseNurseryMap.get(compareVO.getMotherIdcard()).getBegDate());
                    compareVO.setEndDate(houseNurseryMap.get(compareVO.getMotherIdcard()).getEndDate());
                    compareVO.setYearLimit(houseNurseryMap.get(compareVO.getMotherIdcard()).getYearLimit());
                    compareVO.setLandCategories(houseNurseryMap.get(compareVO.getMotherIdcard()).getLandCategories());
                    compareVO.setLandCategoriesName(houseNurseryMap.get(compareVO.getMotherIdcard()).getLandCategoriesName());
                    compareVO.setHouseNature(houseNurseryMap.get(compareVO.getMotherIdcard()).getHouseNature());
                    compareVO.setHouseNatureName(houseNurseryMap.get(compareVO.getMotherIdcard()).getHouseNatureName());
                    compareVO.setQlrName(houseNurseryMap.get(compareVO.getMotherIdcard()).getQlrName());
                    compareVO.setFcAddress(houseNurseryMap.get(compareVO.getMotherIdcard()).getFcAddress());
                }
                //户籍信息
                if(householdMap.get(compareVO.getChildIdcard())!=null){
                    compareVO.setQysj(householdMap.get(compareVO.getChildIdcard()).getQysj());
                    compareVO.setHkAddress(householdMap.get(compareVO.getChildIdcard()).getHkAddress());
                }


                //
                if (!CollectionUtils.isEmpty(kindergartenList)) {
                    fatherIdcardList = kindergartenList.stream().map(EduStudentEnrollKindergarten::getFatherIdcard).distinct().collect(Collectors.toList());
                    motherIdcardList = kindergartenList.stream().map(EduStudentEnrollKindergarten::getMotherIdcard).distinct().collect(Collectors.toList());
                    idcardList = Stream.of(fatherIdcardList, motherIdcardList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
                } else {
                    return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
                }


                if(StringUtils.isBlank(compareVO.getRealPropertyNum())){
                    compareVO.setHouseFlag("0");
                }else{
                    compareVO.setHouseFlag("1");
                }

                if(compareVO.getHkAddress()==null||StringUtils.isBlank(compareVO.getHkAddress())){
                    compareVO.setHouseholdFlag("0");
                }else {
                    compareVO.setHouseholdFlag("1");
                }



            }
        }

        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(EduEnrollKindergartenDictEnum.values()));

        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }


    @Override
    @OpApi(funcCode = "kindergarten0022", title = "幼儿园报名人数信息查询", funcType = FuncTypeEnum.query)
    public StudentEnrollCntVO queryKindergartenBmCnt(EduStudentEnrollKindergartenQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());

        if (vo.getYear() == null) {
            throw new AppException("请输入查询年份");
        }
        int year = eduHelper.thisYear();
        if(year==vo.getYear()){
            //业务期控制校验
            eduHelper.checkOperation("1","YRY002",vo.getAreaCode());
        }
        StudentEnrollCntVO retVO = new StudentEnrollCntVO();
        Integer zrs = 0;
        Integer dsh = 0;
        Integer dlq = 0;
        Integer ylq = 0;


        QueryWrapper<EduStudentEnrollKindergarten> queryWrapper = new QueryWrapper<>();
        List<String> enrollStatusList = new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.ywblq.getType());
        queryWrapper.lambda().select(EduStudentEnrollKindergarten::getEnrollStatus)
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), EduStudentEnrollKindergarten::getSchoolId, vo.getSchoolId())
                .eq(EduStudentEnrollKindergarten::getYear, vo.getYear())
                .in(EduStudentEnrollKindergarten::getEnrollStatus, enrollStatusList)
                .eq(StringUtils.isNotBlank(vo.getConfigType()), EduStudentEnrollKindergarten::getConfigType, vo.getConfigType())
                .eq(StringUtils.isNotBlank(vo.getConfigName()), EduStudentEnrollKindergarten::getConfigName, vo.getConfigName());
        List<EduStudentEnrollKindergarten> list = eduStudentEnrollKindergartenService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            zrs = list.size();
            for (EduStudentEnrollKindergarten enroll : list) {
                if (EnrollStatusFormalEnum.dsh.getType().equals(enroll.getEnrollStatus())) {
                    dsh = dsh + 1;
                }
                if (EnrollStatusFormalEnum.dlq.getType().equals(enroll.getEnrollStatus())) {
                    dlq = dlq + 1;
                }
                if (EnrollStatusFormalEnum.lq.getType().equals(enroll.getEnrollStatus())) {
                    ylq = ylq + 1;
                }
            }

        }

        retVO.setZrs(zrs);
        retVO.setDsh(dsh);
        retVO.setDlq(dlq);
        retVO.setYlq(ylq);
        QueryWrapper<EduSchoolConfig> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper.lambda().select(EduSchoolConfig::getEnrolment)
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), EduSchoolConfig::getSchoolId, vo.getSchoolId())
                .eq(EduSchoolConfig::getAuthStatus, AuthStatusEnum.YES.getType())
                .eq(EduSchoolConfig::getStatus, BoolEnum.TRUE.getType())
                .eq(EduSchoolConfig::getYear, vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getConfigType()), EduSchoolConfig::getConfigType, vo.getConfigType());
        List<EduSchoolConfig> configList = eduSchoolConfigService.list(configQueryWrapper);
        int jhs = 0;
        if (!CollectionUtils.isEmpty(configList)) {
            for (EduSchoolConfig config : configList) {
                Integer count = config.getEnrolment() == null ? 0 : config.getEnrolment();
                jhs = jhs + count;
            }
        }
        retVO.setJhs(jhs);
        if (jhs - ylq > 0) {
            retVO.setLqFlag(true);
        } else {
            retVO.setLqFlag(false);
        }
        return retVO;
    }


    @Override
    @OpApi(funcCode = "kindergarten0023", title = "幼儿园查询摇号数据", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentEnrollKindergartenVO> getKindergartenEnrollLottery(EduStudentEnrollKindergartenQueryVO vo) {

        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduStudentEnrollKindergarten> enrollQueryWrapper = new QueryWrapper<>();
        //摇号数据只取审核通过待录取数据
        enrollQueryWrapper.lambda()
                .eq(EduStudentEnrollKindergarten::getYear,vo.getYear())
                .eq(EduStudentEnrollKindergarten::getSchoolId,vo.getSchoolId())
                .eq(!ObjectUtils.isEmpty(vo.getConfigType()),EduStudentEnrollKindergarten::getConfigType,vo.getConfigType())
                .eq(!ObjectUtils.isEmpty(vo.getConfigName()),EduStudentEnrollKindergarten::getConfigName,vo.getConfigName())
                .eq(EduStudentEnrollKindergarten::getEnrollStatus,"1")
                .orderByAsc(EduStudentEnrollKindergarten::getSerialNum);
        List<EduStudentEnrollKindergarten> list = eduStudentEnrollKindergartenService.list(enrollQueryWrapper);

        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduStudentEnrollKindergarten> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduStudentEnrollKindergartenVO> resultList = Convert.toList(EduStudentEnrollKindergartenVO.class, pageInfo.getList());
        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(EduEnrollKindergartenDictEnum.values()));
        for(EduStudentEnrollKindergartenVO studentEnrollKindergartenVO:resultList){
            if(StringUtils.isNotBlank(studentEnrollKindergartenVO.getSchoolId())){
                EduSchoolVO eduSchoolVO=eduSchoolService.getDetail(studentEnrollKindergartenVO.getSchoolId());
                if(eduSchoolVO!=null){
                    studentEnrollKindergartenVO.setSchoolName(eduSchoolVO.getSchoolName());
                }
            }
        }

        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "kindergarten0024", title = "幼儿园摇号数据导出", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void exportKindergartenEnrollLottery(EduStudentEnrollKindergartenQueryVO vo, HttpServletResponse response) {
        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode(vo.getModelCode());
        ExcelModelVO excelModelVO=excelIntegration.getModel(excelVO);

        String destFilePath = this.tempPath + "/" + IdUtil.fastSimpleUUID() + "." + excelModelVO.getExcelType();
        int pageNum=1;
        setDataEnrollLottery(excelModelVO,null,destFilePath,vo,pageNum);
        String fileName=vo.getFileName();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }
        File file = FileUtil.file(destFilePath);
        BufferedInputStream in = null;
        try {
            in = FileUtil.getInputStream(file);
            ServletUtil.write(response, in, "application/octet-stream;charset=utf-8", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.del(destFilePath);
        }

    }

    @Override
    @OpApi(funcCode = "kindergarten0025", title = "幼儿园摇号数据导入", funcType = FuncTypeEnum.other)
    public KindergartenApplyFileVO inputKindergartenApplyInfo(KindergartenApplyFileVO vo, MultipartFile file) {
        int year = eduHelper.thisYear();
        String schoolId = "";
        if(StringUtils.isEmpty(vo.getSchoolId())) {
            schoolId = SessionUtil.getSessionInfo().getOrgId();
        }else {
            schoolId = vo.getSchoolId();
        }
        QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper=new QueryWrapper<>();
        brochureQueryWrapper.lambda().eq(EduEnrollmenBrochure::getYear,year)
                .eq(EduEnrollmenBrochure::getSchoolId,schoolId);
        EduEnrollmenBrochure eduEnrollmenBrochure=eduEnrollmenBrochureService.getOne(brochureQueryWrapper,false);
        if(eduEnrollmenBrochure==null){
            throw new AppException("未找到学校招生方案信息");
        }
        EduSchool eduSchool=eduSchoolService.getById(schoolId);

        if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                throw new AppException("招生已停止，不能导入");
        }

        List<EduStudentEnrollKindergartenVO> kinderEnrollVOList =new ArrayList<>();
        List<EduStudentEnrollKindergartenVO> kinderEnrollVOList2 =new ArrayList<>();
        ExcelVO excelVO = Convert.convert(ExcelVO.class,vo);
        ExcelModelVO excelModelVO = excelIntegration.getModel(excelVO);
        InputStream in = null;
        try {
            in = file.getInputStream();
            List<Map<String, Object>> list = excelCommonHelper.readExcel(excelModelVO, in, true);
            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(list);
            kinderEnrollVOList2 = jsonArray.toJavaList(EduStudentEnrollKindergartenVO.class);

            //捆绑摇号
            for (EduStudentEnrollKindergartenVO kinderVo : kinderEnrollVOList2) {
                if(kinderVo.getApplyIdS().contains(",")){
                    String[] applyIdArray = kinderVo.getApplyIdS().split(",");
                    String[] fullNameArray = kinderVo.getChildFullName().split(",");
                    String[] idCardArray = new String[]{};
                    if(StringUtils.isNotEmpty(kinderVo.getChildIdcard())){
                        idCardArray = kinderVo.getChildIdcard().split(",");
                    }
                    for (int i = 0; i < applyIdArray.length; i++) {
                        EduStudentEnrollKindergartenVO enroll = new EduStudentEnrollKindergartenVO();
                        enroll.setApplyId(Long.parseLong(applyIdArray[i]));
                        enroll.setChildFullName(fullNameArray[i]);
                        if(idCardArray.length>0) {
                            enroll.setChildIdcard(idCardArray[i]);
                        }
                        enroll.setSerialNum(kinderVo.getSerialNum());
                        kinderEnrollVOList.add(enroll);
                    }
                }else {
                    kinderVo.setApplyId(Long.parseLong(kinderVo.getApplyIdS()));
                    kinderEnrollVOList.add(kinderVo);
                }
            }

        } catch (IOException e) {
            throw new AppException("导入异常："+e.getMessage());
        }
        if(CollectionUtils.isEmpty(kinderEnrollVOList)){
            throw new AppException("导入数据不能为空");
        }

        for(EduStudentEnrollKindergartenVO item: kinderEnrollVOList) {
            if(item.getSerialNum() == null) {
                throw new AppException("存在摇号序号为空的条目！");
            }
        }

        String redisKey=REDIS_YHDR+schoolId;
        if(redisHelper.hasKey(redisKey)){
            throw new AppException("上一次导入正在处理中，不能导入");
        }else{
            redisHelper.set(redisKey,"1",300);
        }
        //过滤报名编号为空数据
        kinderEnrollVOList=kinderEnrollVOList.stream()
                .filter(
                        filterItem ->!ObjectUtils.isEmpty(filterItem.getApplyId()))
                .collect(Collectors.toList());

        List<EduStudentEnrollKindergartenVO> errorList = new ArrayList<>();
        QueryWrapper<EduStudentEnrollKindergarten> existsQueryWrapper = new QueryWrapper<>();
        existsQueryWrapper
                .lambda()
                .eq(EduStudentEnrollKindergarten::getSchoolId,schoolId)
                .in(
                        EduStudentEnrollKindergarten::getApplyId,
                        kinderEnrollVOList.stream()
                                .map(EduStudentEnrollKindergartenVO::getApplyId)
                                .collect(Collectors.toList()));
        List<EduStudentEnrollKindergarten> studentEnrollList =
                eduStudentEnrollKindergartenService.list(existsQueryWrapper);
        if(CollectionUtils.isEmpty(studentEnrollList)){
            redisHelper.del(redisKey);
            throw new AppException("导入的报名编号在系统中未匹配到数据");
        }

        List<Long> applyIdList =
                studentEnrollList.stream()
                        .map(EduStudentEnrollKindergarten::getApplyId)
                        .collect(Collectors.toList());
        List<String> idcardList = new ArrayList<>();
        List<EduStudentEnrollKindergarten> successList = new ArrayList<>();
        kinderEnrollVOList.forEach(
                item -> {
                    if (item.getApplyId() == null || item.getSerialNum() == null) {
                        redisHelper.del(redisKey);
                        throw new AppException("模板有误!");
                    }
                    String remarks = "";
                    boolean flag = false;
                    if (!ObjectUtils.isEmpty(item.getChildIdcard())) {
                        if (idcardList.contains(item.getChildIdcard())) {
                            remarks += "存在重复学生身份证！";
                            flag = true;
                        } else {
                            idcardList.add(item.getChildIdcard());
                        }
                    }
                    if (!applyIdList.contains(item.getApplyId())) {
                        remarks += "根据报名编号查询不到学生信息！";
                        flag = true;
                    } else {
                        EduStudentEnrollKindergarten eduStudentEnroll =
                                studentEnrollList.stream()
                                        .filter(
                                                filterItem ->
                                                        Objects.equals(
                                                                filterItem.getApplyId(),
                                                                item.getApplyId()))
                                        .collect(Collectors.toList())
                                        .get(0);
                        if(eduStudentEnroll.getEnrollStatus().equals(EnrollStatusFormalEnum.lq.getType())){
                            redisHelper.del(redisKey);
                            throw new AppException("录取工作已开始后不能导入摇号结果");
                        }
                        if(!eduStudentEnroll.getEnrollStatus().equals(EnrollStatusFormalEnum.dlq.getType())){
                            redisHelper.del(redisKey);
                            throw new AppException("数据异常：人员数据不是待录取状态，请联系管理员查找原因");
                        }
                        if (!ObjectUtils.isEmpty(item.getChildFullName())
                                && !StringUtils.equals(
                                item.getChildFullName(), eduStudentEnroll.getChildFullName())) {
                            remarks += "学生姓名预系统中的不匹配！";
                            flag = true;
                        }
                        if (!ObjectUtils.isEmpty(item.getChildIdcard())
                                && !StringUtils.equals(
                                item.getChildIdcard(), eduStudentEnroll.getChildIdcard())) {
                            remarks += "学生证件号码与系统中的不匹配！";
                            flag = true;
                        }
                        item.setFormDetailId(eduStudentEnroll.getFormDetailId());
                        if (!flag) {
                            eduStudentEnroll.setSerialNum(item.getSerialNum());
                            successList.add(eduStudentEnroll);

                        }
                    }
                    if (flag) {
                        item.setRemarks(remarks);
                        errorList.add(item);
                    }
                });
        vo.setErrorList(errorList);
        vo.setErrorId(IdUtil.simpleUUID());

        if(!CollectionUtils.isEmpty(successList)){
            eduStudentEnrollKindergartenService.updateBatchById(successList);
            vo.setSuccessList(Convert.toList(EduStudentEnrollKindergartenVO.class,successList));
        }
        redisHelper.del(redisKey);
        return vo;
    }


    @Override
    @OpApi(funcCode = "kindergarten0026", title = "幼儿园校验是否可以摇号导出", funcType = FuncTypeEnum.query)
    public void checkKindergartenExp(EduStudentEnrollKindergartenQueryVO vo) {
        String schoolId=vo.getSchoolId();
        if(StringUtils.isBlank(schoolId)){
            schoolId=SessionUtil.getSessionInfo().getOrgId();
        }
        if(StringUtils.isBlank(vo.getConfigType())){
            throw new AppException("请先选择幼儿园学段");
        }
        int year = eduHelper.thisYear();

        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        //判断是否有未审核数据
        QueryWrapper<EduStudentEnrollKindergarten> wshQuery=new QueryWrapper<>();
        wshQuery.lambda().eq(EduStudentEnrollKindergarten::getSchoolId,schoolId)
                .eq(EduStudentEnrollKindergarten::getAreaCode,vo.getAreaCode())
                .eq(EduStudentEnrollKindergarten::getYear,year)
                .eq(EduStudentEnrollKindergarten::getConfigType,vo.getConfigType())
                .eq(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.dsh.getType())
                ;
        long wshCount=eduStudentEnrollKindergartenService.count(wshQuery);
        if(wshCount>0){
            throw new AppException("存在未审核数据，请先审核后导出");
        }
        //判断是否存在摇号排序号，存在的情况下不允许导出
        QueryWrapper<EduStudentEnrollKindergarten> pxhQuery=new QueryWrapper<>();
        pxhQuery.lambda().eq(EduStudentEnrollKindergarten::getSchoolId,schoolId)
                .eq(EduStudentEnrollKindergarten::getAreaCode,vo.getAreaCode())
                .eq(EduStudentEnrollKindergarten::getYear,year)
                .eq(EduStudentEnrollKindergarten::getConfigType,vo.getConfigType())
                .eq(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.dlq.getType())
                .isNotNull(EduStudentEnrollKindergarten::getSerialNum);
        long pxhCount=eduStudentEnrollKindergartenService.count(pxhQuery);
        if(pxhCount>0){
            throw new AppException("已存在摇号排序号，不能导出");
        }
        //判断审核通过是否大于计划数

        //待录取人数
        QueryWrapper<EduStudentEnrollKindergarten> dlqQuery=new QueryWrapper<>();
        dlqQuery.lambda().eq(EduStudentEnrollKindergarten::getSchoolId,schoolId)
                .eq(EduStudentEnrollKindergarten::getAreaCode,vo.getAreaCode())
                .eq(EduStudentEnrollKindergarten::getYear,year)
                .eq(EduStudentEnrollKindergarten::getConfigType,vo.getConfigType())
                .eq(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.dlq.getType());
        long dlyCount=eduStudentEnrollKindergartenService.count(dlqQuery);
        if(dlyCount==0){
            throw new AppException("没有待录取数据，不能导出");
        }
        QueryWrapper<EduSchoolConfig> configQueryWrapper=new QueryWrapper<>();
        configQueryWrapper.lambda().select(EduSchoolConfig::getEnrolment)
                .eq(EduSchoolConfig::getSchoolId,schoolId)
                .eq(EduSchoolConfig::getAreaCode,vo.getAreaCode())
                .eq(EduSchoolConfig::getYear,year)
                .eq(EduSchoolConfig::getAuthStatus,AuthStatusEnum.YES.getType())
                .eq(EduSchoolConfig::getStatus,BoolEnum.TRUE.getType())
                .eq(EduSchoolConfig::getConfigType,vo.getConfigType());
        QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper=new QueryWrapper<>();
        brochureQueryWrapper.lambda().eq(EduEnrollmenBrochure::getYear,year)
                .eq(EduEnrollmenBrochure::getSchoolId,schoolId);
        EduEnrollmenBrochure eduEnrollmenBrochure=eduEnrollmenBrochureService.getOne(brochureQueryWrapper,false);
        if(eduEnrollmenBrochure==null){
            throw new AppException("未找到招生方案信息");
        }
        EduSchool eduSchool=eduSchoolService.getById(schoolId);
        if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                throw new AppException("招生已停止，不能导出");
          }

        EduSchoolConfig eduSchoolConfig=eduSchoolConfigService.getOne(configQueryWrapper,false);
        if(eduSchoolConfig==null){
            throw new AppException("未配置招生计划");
        }
        //计划人数
        Integer enrolment=0;
        if(eduSchoolConfig!=null){
            enrolment=eduSchoolConfig.getEnrolment()==null?0:eduSchoolConfig.getEnrolment();
        }
        //已录取人数
        QueryWrapper<EduStudentEnrollKindergarten> ylqQuery=new QueryWrapper<>();
        ylqQuery.lambda().eq(EduStudentEnrollKindergarten::getSchoolId,schoolId)
                .eq(EduStudentEnrollKindergarten::getAreaCode,vo.getAreaCode())
                .eq(EduStudentEnrollKindergarten::getYear,year)
                .eq(EduStudentEnrollKindergarten::getConfigType,vo.getConfigType())
                .eq(EduStudentEnrollKindergarten::getEnrollStatus,EnrollStatusFormalEnum.lq.getType());
        long ylqCount=eduStudentEnrollKindergartenService.count(ylqQuery);

        if(ylqCount+dlyCount<=enrolment){
            throw new AppException("录取人数小于计划数，无需摇号。");
        }
    }


    @Override
    @OpApi(funcCode = "kindergarten0028", title = "幼儿园清除缓存", funcType = FuncTypeEnum.query)
    public void clearnurseryhc(EduStudentEnrollKindergartenQueryVO vo) {
        String formDetailId = vo.getFormDetailId();
        Assert.hasText(formDetailId, "报名id不能为空");

        EduStudentEnrollKindergarten detail = eduStudentEnrollKindergartenService.getById(formDetailId);
        Assert.notNull(detail, "查询不到报名信息");
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getChildIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getFatherIdcard());
        enrollClearCacheHelper.clearCacheMyEnroll(detail.getMotherIdcard());

    }


    @Override
    @OpApi(funcCode = "kindergarten0029", title = "幼儿园清除缓存", funcType = FuncTypeEnum.query)
    public void clearNurseryQueryCache(EduStudentEnrollKindergartenQueryVO vo) {
        LambdaQueryWrapper<EduStudentEnrollKindergarten> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(!ObjectUtils.isEmpty(vo.getYear()), EduStudentEnrollKindergarten::getYear, vo.getYear())
                .eq(
                        !ObjectUtils.isEmpty(vo.getEnrollStatus()),
                        EduStudentEnrollKindergarten::getEnrollStatus,
                        vo.getEnrollStatus())
                .eq(
                        !ObjectUtils.isEmpty(vo.getSource()),
                        EduStudentEnrollKindergarten::getSource,
                        vo.getSource())
                .eq(
                        !ObjectUtils.isEmpty(vo.getAreaCode()),
                        EduStudentEnrollKindergarten::getAreaCode,
                        vo.getAreaCode())
                .like(
                        !ObjectUtils.isEmpty(vo.getChildFullName()),
                        EduStudentEnrollKindergarten::getChildFullName,
                        vo.getChildFullName())
                .eq(
                        !ObjectUtils.isEmpty(vo.getChildIdcard()),
                        EduStudentEnrollKindergarten::getChildIdcard,
                        vo.getChildIdcard())
                .eq(
                        !ObjectUtils.isEmpty(vo.getConfigName()),
                        EduStudentEnrollKindergarten::getConfigName,
                        vo.getConfigName())
                .eq(
                        !ObjectUtils.isEmpty(vo.getChildCardType()),
                        EduStudentEnrollKindergarten::getChildCardType,
                        vo.getChildCardType())
                .eq(
                        !ObjectUtils.isEmpty(vo.getBirthYmd()),
                        EduStudentEnrollKindergarten::getBirthYmd,
                        vo.getBirthYmd())
                .eq(!ObjectUtils.isEmpty(vo.getSex()), EduStudentEnrollKindergarten::getSex, vo.getSex())
                .like(
                        !ObjectUtils.isEmpty(vo.getChildShortName()),
                        EduStudentEnrollKindergarten::getChildShortName,
                        vo.getChildShortName())
                .like(
                        !ObjectUtils.isEmpty(vo.getHouseholdPlace()),
                        EduStudentEnrollKindergarten::getHouseholdPlace,
                        vo.getHouseholdPlace())
                .like(
                        !ObjectUtils.isEmpty(vo.getAddress()),
                        EduStudentEnrollKindergarten::getAddress,
                        vo.getAddress())
                .like(
                        !ObjectUtils.isEmpty(vo.getFatherName()),
                        EduStudentEnrollKindergarten::getFatherName,
                        vo.getFatherName())
                .eq(
                        !ObjectUtils.isEmpty(vo.getFatherIdcard()),
                        EduStudentEnrollKindergarten::getFatherIdcard,
                        vo.getFatherIdcard())
                .like(
                        !ObjectUtils.isEmpty(vo.getFatherWork()),
                        EduStudentEnrollKindergarten::getFatherWork,
                        vo.getFatherWork())
                .eq(
                        !ObjectUtils.isEmpty(vo.getFatherPhone()),
                        EduStudentEnrollKindergarten::getFatherPhone,
                        vo.getFatherPhone())
                .like(
                        !ObjectUtils.isEmpty(vo.getMotherName()),
                        EduStudentEnrollKindergarten::getMotherName,
                        vo.getMotherName())
                .eq(
                        !ObjectUtils.isEmpty(vo.getMotherIdcard()),
                        EduStudentEnrollKindergarten::getMotherIdcard,
                        vo.getMotherIdcard())
                .like(
                        !ObjectUtils.isEmpty(vo.getMotherWork()),
                        EduStudentEnrollKindergarten::getMotherWork,
                        vo.getMotherWork())
                .eq(
                        !ObjectUtils.isEmpty(vo.getMotherPhone()),
                        EduStudentEnrollKindergarten::getMotherPhone,
                        vo.getMotherPhone())
                .eq(
                        !ObjectUtils.isEmpty(vo.getAuthStatus()),
                        EduStudentEnrollKindergarten::getAuthStatus,
                        vo.getAuthStatus())
                .eq(
                        !ObjectUtils.isEmpty(vo.getConfigType()),
                        EduStudentEnrollKindergarten::getConfigType,
                        vo.getConfigType())
                .eq(!ObjectUtils.isEmpty(vo.getSchoolId()),EduStudentEnrollKindergarten::getSchoolId, vo.getSchoolId());
        if(StringUtils.isNotBlank(vo.getAdmitFlag())){
            if(BoolEnum.TRUE.getType().equalsIgnoreCase(vo.getAdmitFlag())){
                queryWrapper.eq(EduStudentEnrollKindergarten::getAdmitFlag,vo.getAdmitFlag());
            }else if(BoolEnum.FALSE.getType().equalsIgnoreCase(vo.getAdmitFlag())){
                queryWrapper.eq(EduStudentEnrollKindergarten::getAdmitFlag,vo.getAdmitFlag());
            }else{
                queryWrapper.isNull(EduStudentEnrollKindergarten::getAdmitFlag);
            }
        }

        List<EduStudentEnrollKindergarten> list = eduStudentEnrollKindergartenService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return ;
        }

        for (EduStudentEnrollKindergarten detail : list) {
            enrollClearCacheHelper.clearCacheMyEnroll(detail.getChildIdcard());
            enrollClearCacheHelper.clearCacheMyEnroll(detail.getFatherIdcard());
            enrollClearCacheHelper.clearCacheMyEnroll(detail.getMotherIdcard());
        }




    }

    public PageInfo<EduStudentEnrollKindergartenVO> expKindergartenEnrollLotteryList(EduStudentEnrollKindergartenQueryVO vo) {

        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduStudentEnrollKindergarten> enrollQueryWrapper = new QueryWrapper<>();
        //摇号数据只取审核通过待录取数据
        enrollQueryWrapper.lambda()
                .eq(EduStudentEnrollKindergarten::getYear,vo.getYear())
                .eq(EduStudentEnrollKindergarten::getSchoolId,vo.getSchoolId())
                .eq(!ObjectUtils.isEmpty(vo.getConfigType()),EduStudentEnrollKindergarten::getConfigType,vo.getConfigType())
                .eq(!ObjectUtils.isEmpty(vo.getConfigName()),EduStudentEnrollKindergarten::getConfigName,vo.getConfigName())
                .eq(EduStudentEnrollKindergarten::getEnrollStatus,"1")
                .and(q ->q
                    .eq(EduStudentEnrollKindergarten::getBindMianFlag,"1")
                    .or()
                    .isNull(EduStudentEnrollKindergarten::getBindFlag)
                    .or()
                    .eq(EduStudentEnrollKindergarten::getBindFlag,"0")
                   )
                .orderByAsc(EduStudentEnrollKindergarten::getSerialNum);
        List<EduStudentEnrollKindergarten> list = eduStudentEnrollKindergartenService.list(enrollQueryWrapper);

        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduStudentEnrollKindergarten> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduStudentEnrollKindergartenVO> resultList = Convert.toList(EduStudentEnrollKindergartenVO.class, pageInfo.getList());
        for (EduStudentEnrollKindergartenVO kindergartenVO : resultList) {
            kindergartenVO.setChildFullNameTm(getFullName(kindergartenVO.getChildFullName()));
            kindergartenVO.setChildIdcardTm(getIdcard(kindergartenVO.getChildIdcard()));
            if("1".equals(kindergartenVO.getBindMianFlag())) {
                QueryWrapper<EduStudentEnrollKindergarten> kindergartenQueryWrapper = new QueryWrapper<>();
                kindergartenQueryWrapper.lambda().eq(EduStudentEnrollKindergarten::getYear, vo.getYear())
                        .eq(EduStudentEnrollKindergarten::getSchoolId, vo.getSchoolId())
                        .eq(!ObjectUtils.isEmpty(vo.getConfigType()),EduStudentEnrollKindergarten::getConfigType,vo.getConfigType())
                        .eq(!ObjectUtils.isEmpty(vo.getConfigName()),EduStudentEnrollKindergarten::getConfigName,vo.getConfigName())
                        .eq(EduStudentEnrollKindergarten::getEnrollStatus,"1")
                        .eq(EduStudentEnrollKindergarten::getBindMianFlag,"0")
                        .eq(EduStudentEnrollKindergarten::getBindIdcard, kindergartenVO.getChildIdcard());
                List<EduStudentEnrollKindergarten> enrollList = eduStudentEnrollKindergartenService.list(kindergartenQueryWrapper);
                if (!CollectionUtils.isEmpty(enrollList)) {
                    for (EduStudentEnrollKindergarten enroll : enrollList) {
                        EduStudentEnrollKindergartenVO enrollVO = Convert.convert(EduStudentEnrollKindergartenVO.class, enroll);
                        kindergartenVO.setApplyIdS(kindergartenVO.getApplyId()+","+enrollVO.getApplyId());
                        kindergartenVO.setChildFullName(kindergartenVO.getChildFullName()+","+enrollVO.getChildFullName());
                        kindergartenVO.setChildIdcard(kindergartenVO.getChildIdcard()+","+enrollVO.getChildIdcard());
                        kindergartenVO.setChildIdcardTm(kindergartenVO.getChildIdcardTm()+","+getIdcard(enrollVO.getChildIdcard()));
                        kindergartenVO.setChildFullNameTm(kindergartenVO.getChildFullNameTm()+","+getFullName(enrollVO.getChildFullName()));


                    }
                }
            }else {
                kindergartenVO.setApplyIdS(kindergartenVO.getApplyId()+"");
            }
        }
        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(EduEnrollKindergartenDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "kindergarten0027", title = "幼儿园校验是否可以绑定", funcType = FuncTypeEnum.query)
    public List<BindEnrollVO> checkBind(BindEnrollQueryVO vo) {
        if (StringUtils.isBlank(vo.getSchoolId())) {
            throw new AppException("报名学校id不能为空");
        }
        String birthYmd = vo.getBirthYmd();
        if (StringUtils.isBlank(vo.getIdcard())) {
            throw new AppException("当前报名孩子证件号码不能为空");
        } else {
            if (!IdcardUtil.isValidCard(vo.getIdcard())) {
                if (StringUtils.isBlank(vo.getBirthYmd())) {
                    throw new AppException("当前报名孩子出生日期不能为空");
                } else {
                    if (vo.getBirthYmd().length() >= 8) {
                        birthYmd = vo.getBirthYmd().replaceAll("-", "").replaceAll("/", "");
                    } else if (vo.getBirthYmd().length() == 6) {
                        birthYmd = vo.getBirthYmd() + "01";
                    } else {
                        throw new AppException("出生日期格式不正确");
                    }
                }
            } else {
                birthYmd = IdcardUtil.getBirth(vo.getIdcard());
            }
        }
        if (StringUtils.isBlank(vo.getFatherIdcard()) && StringUtils.isBlank(vo.getMotherIdcard())) {
            throw new AppException("当前报名孩子父亲或者母亲证件号码为空");
        }
        List<BindEnrollVO> bindEnrollVOS = new ArrayList<>();
        Integer year = eduHelper.thisYear();
        if(StringUtils.isNotBlank(vo.getFatherIdcard())) {
            QueryWrapper<EduStudentEnrollKindergarten> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(EduStudentEnrollKindergarten::getChildIdcard, EduStudentEnrollKindergarten::getChildFullName, EduStudentEnrollKindergarten::getBindFlag, EduStudentEnrollKindergarten::getConfigType, EduStudentEnrollKindergarten::getConfigName, EduStudentEnrollKindergarten::getFormId)
                    .eq(EduStudentEnrollKindergarten::getSchoolId, vo.getSchoolId())
                    .eq(EduStudentEnrollKindergarten::getYear, year)
                    .eq(EduStudentEnrollKindergarten::getBirthYmd, birthYmd)
                    .eq(EduStudentEnrollKindergarten::getFatherIdcard, vo.getFatherIdcard())
                    .eq(EduStudentEnrollKindergarten::getEnrollStatus, EnrollStatusFormalEnum.dsh.getType());
            List<EduStudentEnrollKindergarten> faList = eduStudentEnrollKindergartenService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(faList)) {
                for (EduStudentEnrollKindergarten kindergarten : faList) {
                    BindEnrollVO bindEnrollVO = new BindEnrollVO();
                    bindEnrollVO.setBindFlag(kindergarten.getBindFlag());
                    bindEnrollVO.setIdcard(kindergarten.getChildIdcard());
                    bindEnrollVO.setFullName(kindergarten.getChildFullName());
                    bindEnrollVO.setConfigName(kindergarten.getConfigName());
                    bindEnrollVO.setConfigType(kindergarten.getConfigType());
                    bindEnrollVO.setFormId(kindergarten.getFormId());
                    bindEnrollVOS.add(bindEnrollVO);
                }
                return bindEnrollVOS;
            }
        }
        if(StringUtils.isNotBlank(vo.getMotherIdcard())) {
            QueryWrapper<EduStudentEnrollKindergarten> moQuery = new QueryWrapper<>();
            moQuery.lambda().select(EduStudentEnrollKindergarten::getChildIdcard, EduStudentEnrollKindergarten::getChildFullName, EduStudentEnrollKindergarten::getBindFlag, EduStudentEnrollKindergarten::getConfigType, EduStudentEnrollKindergarten::getConfigName, EduStudentEnrollKindergarten::getFormId)
                    .eq(EduStudentEnrollKindergarten::getSchoolId, vo.getSchoolId())
                    .eq(EduStudentEnrollKindergarten::getYear, year)
                    .eq(EduStudentEnrollKindergarten::getBirthYmd, birthYmd)
                    .eq(EduStudentEnrollKindergarten::getMotherIdcard, vo.getMotherIdcard())
                    .eq(EduStudentEnrollKindergarten::getEnrollStatus, EnrollStatusFormalEnum.dsh.getType());
            List<EduStudentEnrollKindergarten> moList = eduStudentEnrollKindergartenService.list(moQuery);
            if (!CollectionUtils.isEmpty(moList)) {
                for (EduStudentEnrollKindergarten kindergarten : moList) {
                    BindEnrollVO bindEnrollVO = new BindEnrollVO();
                    bindEnrollVO.setBindFlag(kindergarten.getBindFlag());
                    bindEnrollVO.setIdcard(kindergarten.getChildIdcard());
                    bindEnrollVO.setFullName(kindergarten.getChildFullName());
                    bindEnrollVO.setConfigName(kindergarten.getConfigName());
                    bindEnrollVO.setConfigType(kindergarten.getConfigType());
                    bindEnrollVO.setFormId(kindergarten.getFormId());
                    bindEnrollVOS.add(bindEnrollVO);
                }
                return bindEnrollVOS;
            }
        }
        return new ArrayList<>();
    }

    private void setDataEnrollLottery(ExcelModelVO excelModelVO, ExcelWriter excelWriter, String destFilePath, EduStudentEnrollKindergartenQueryVO vo, int pageNum){
        vo.setPageNum(pageNum);
        vo.setPageSize(500);
        boolean closeFlag=false;
        try {
            PageInfo<EduStudentEnrollKindergartenVO> pageInfo= this.expKindergartenEnrollLotteryList(vo);
            String total=String.valueOf(pageInfo.getTotal());
            List<Object> list=new ArrayList<>();
            if(!CollectionUtils.isEmpty(pageInfo.getList())){
                for(EduStudentEnrollKindergartenVO kindergartenVo:pageInfo.getList()){
                    list.add(kindergartenVo);
                }
            }
            if(pageNum==1){
                if(excelWriter==null){
                    excelWriter=excelCommonHelper.createExcelWriter(excelModelVO,destFilePath,Integer.parseInt(total));
                }
                excelCommonHelper.writeBean(excelWriter,list);
            }else{
                excelCommonHelper.writeBean(excelWriter,list);
            }
            if(pageInfo.isHasNextPage()){
                pageNum=pageNum+1;
                setDataEnrollLottery(excelModelVO,excelWriter,destFilePath,vo,pageNum);
            }else{
                closeFlag=true;
            }
        }catch (AppException appEx){
            throw appEx;
        }catch (Exception e){
            throw new AppException("调用自定义写入服务异常:" + e.getMessage());
        }finally {
            if(closeFlag&&excelWriter!=null){
                excelWriter.close();
            }
        }
    }




    private void setData(ExcelModelVO excelModelVO, ExcelWriter excelWriter, String destFilePath, EduStudentEnrollKindergartenQueryVO vo, int pageNum){
        vo.setPageNum(pageNum);
        vo.setPageSize(500);
        boolean closeFlag = false;
        try {
            PageInfo<EduStudentEnrollKindergartenVO> pageInfo= getList(vo);
            String total=String.valueOf(pageInfo.getTotal());
            List<Map<String,Object>> list=new ArrayList<>();
            if(!CollectionUtils.isEmpty(pageInfo.getList())){
                for(EduStudentEnrollKindergartenVO studentEnrollVO:pageInfo.getList()){
                    list.add(BeanUtil.beanToMap(studentEnrollVO,false,true));
                }
            }
            if(pageNum==1){
                if(excelWriter==null){
                    excelWriter=excelCommonHelper.createExcelWriter(excelModelVO,destFilePath,Integer.parseInt(total));
                }
                excelCommonHelper.writeMap(excelWriter,list);
            }else{
                excelCommonHelper.writeMap(excelWriter,list);
            }
            if(pageInfo.isHasNextPage()){
                pageNum=pageNum+1;
                setData(excelModelVO,excelWriter,destFilePath,vo,pageNum);
            }else {
                closeFlag = true;
            }
        }catch (AppException appEx){
            throw appEx;
        }catch (Exception e){
            throw new AppException("调用自定义写入服务异常:" + e.getMessage());
        }finally {
            if(closeFlag&&excelWriter!=null){
                excelWriter.close();
            }
        }
    }
    private synchronized void saveFormDetail(
            EduStudentEnrollKindergarten formDetail,
            int year,
            int yearId,
            String schoolCategoryId,
            String schoolNum,
            String orderNoId) {
        String bmKey = EduCache.EDU_ENROLL_KINDERGARTEN_ZS + formDetail.getChildIdcard();

        ////缓存中没有则加锁
        RLock lock = redissonClient.getLock(EduCache.EDU_YEY_ENROLL + formDetail.getSchoolId()+":"+schoolCategoryId+":"+orderNoId);
        boolean res;
        try {
            //等待锁10s,锁租约时间20s
            res = lock.tryLock(3000, 20000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            throw new AppException("当前时间段该学校报名人数过多，系统繁忙，请稍后再试", e);
        }
        String redisKey="yeyEnroll:"+formDetail.getSchoolId()+":"+orderNoId;
        if (res) {
            if(formDetail.getApplyId()==null){

                Long applyId =0L;
                if(redisHelper.hasKey(redisKey)) {
                    Long redisNum= (Long) redisHelper.get(redisKey);
                    applyId=redisNum+1;
                    redisHelper.set(redisKey,applyId,86400);
                }else {
                    applyId = eduStudentEnrollKindergartenService.queryMaxApplyId(formDetail.getFormId());
                    if (ObjectUtils.isEmpty(applyId)) {
                        String numId = StringUtils.leftPad( "1", 4, "0");
                        applyId = Long.parseLong(yearId + schoolCategoryId + schoolNum + orderNoId + numId);
                    } else {
                        applyId = applyId + 1;
                    }
                    redisHelper.set(redisKey,applyId,86400);
                }

                formDetail.setApplyId(applyId);
            }

            formDetail.setYear(year);
            if (StringUtils.isBlank(formDetail.getAdmitFlag())){
                formDetail.setAdmitFlag(null);
            }
            if (StringUtils.isBlank(formDetail.getAuthStatus())){
                formDetail.setAuthStatus(AuthStatusEnum.NODO.getType());
            }
            if (StringUtils.isBlank(formDetail.getEnrollStatus())){
                formDetail.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
            }
            try {
                eduStudentEnrollKindergartenService.save(formDetail);
                enrollClearCacheHelper.clearCacheMyEnroll(formDetail.getChildIdcard());
                enrollClearCacheHelper.clearCacheMyEnroll(formDetail.getFatherIdcard());
                enrollClearCacheHelper.clearCacheMyEnroll(formDetail.getMotherIdcard());
                redisHelper.set(bmKey, true, 600);
                return;
            } catch (Exception e) {
                redisHelper.del(redisKey);
                throw new AppException("当前时间段该学校报名人数过多，系统繁忙，请稍后再试",e);
            } finally {
                lock.unlock();
            }
        }
        throw new AppException("当前时间段该学校报名人数过多，系统繁忙，请稍后再试");
    }

    private String getFullName(String str){
        if(StringUtils.isBlank(str)){
            return str;
        }
        if(str.length()<3){
            return str.substring(0,1)+"*";
        }else{
            int le=str.length()-1;
            return str.substring(0,1)+"*"+str.substring(le);
        }

    }
    //证件号码脱敏
    private String getIdcard(String str){
        if(StringUtils.isBlank(str)){
            return str;
        }
        if (str.length()==18) {
            return str.substring(0,6)+"********"+str.substring(14,18);
        }else{
            int len=str.length();
            String  enCard=str.substring(0, 2);
            for(int i=0;i<len-4;i++){
                enCard=enCard+"*";
            }
            enCard=enCard+str.substring(len-3);
            return enCard;
        }
    }
}
